package com.binguo.api.baidu;

import com.binguo.api.baidu.localrec.Res;
import com.binguo.api.baidu.localrec.ResResult;
import com.binguo.api.baidu.model.BaiduSearchResult;
import com.binguo.api.baidu.model.Dishes;
import com.binguo.api.baidu.model.ImgTag;
import com.binguo.api.baidu.model.Result;
import com.binguo.api.businessmodel.ProductImgDetailModel;
import com.binguo.api.businessmodel.ProductImgModel;
import com.binguo.api.form.ProductCorrectForm;
import com.binguo.api.form.ProductCorrectItemForm;
import com.binguo.api.huawei.imagesearch.Demo.ImageSearchDemo;
import com.binguo.api.huawei.imagesearch.model.HuaweiProduct;
import com.binguo.api.huawei.imagesearch.model.NeedReplacedProduct;
import com.binguo.api.huawei.imagesearch.model.RecResult;
import com.binguo.api.imgrec.ImgRecResult;
import com.binguo.api.imgrec.Results;
import com.binguo.api.response.mealset.PackageContent;
import com.binguo.api.response.product.*;
import com.binguo.api.schedule.DataLoadService;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.*;
import com.binguo.common.util.ImageBase64Util;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.service.ProductService;
import com.binguo.youtu.sign.Base64Util;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class BaiduRecUtil {

    private static Logger logger = LoggerFactory.getLogger(BaiduRecUtil.class);

    private static String appid = "16805085";
    private static String apiKey = "3t7PQUPeThDcPyEpUNh8UHZA";
    private static String securityKey = "SciYNqyHOip2GnS5jDjw5nCgeaqFA85w";

    public static String tokenKey = "baiduToken";
    private static String baiduAppidKey = "baiduAppid";


    public static String tokenKeyCur = "baiduTokenCur";
    private static String baiduAppidKeyCur = "baiduAppidCur";
    private static Long tokenExpireTime = 0l;

    @Resource
    private ShopBaiduUrlMapper shopBaiduUrlMapper;
    @Resource
    public ProductSubMapper productSubMapper;
    @Resource
    public ProductMapper productMapper;

    @Resource
    private LogProductRecMapper logProductRecMapper;

    @Resource
    public LogProductImgFromUserMapper logProductImgFromUserMapper;

    @Resource
    public ProductImgJsonInfoMapper productImgJsonInfoMapper;

    @Resource
    private LogShopBaiduImgDelMapper logShopBaiduImgDelMapper;
    @Resource
    public BranchMapper branchMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public RestTemplate restTemplate = new RestTemplate();

    public HttpHeaders DEFAULT_JSON_HEADER;

    public HttpHeaders DEFAULT_JSON_HEADER_UTF8;

    public String recIp;

    public String ipAddress;

    public static int width = 30;

    public Product noneRecProduct = new Product();


    public BaiduRecUtil(){
        DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        DEFAULT_JSON_HEADER_UTF8 = new HttpHeaders();
        DEFAULT_JSON_HEADER_UTF8.setContentType(MediaType.APPLICATION_JSON_UTF8);


        recIp = System.getenv("recIp");

        if (StringUtils.isEmpty(recIp)) {
            recIp = "172.17.0.5";//newbinguo
        }

        this.ipAddress = System.getenv().get("ipAddress");

        if (this.ipAddress == null) {
            this.ipAddress = "";
        }

        noneRecProduct.setName("未识别菜品");
        noneRecProduct.setId(1);
        noneRecProduct.setPrice(1l);

    }


    public void setKey(String key, Object value, long time) {
        try {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Object getKey(String key) {
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public String getBaiduToken(Integer shopId, Integer branchId) {
        Object tokenObj = getKey(tokenKey + shopId + branchId);
        logger.info("getBaiduToken,key={}, value={}", tokenKey + shopId + branchId, tokenObj);


        if (tokenObj == null) {
            Condition condition = new Condition(ShopBaiduUrl.class);
            condition.or().andEqualTo("shopId", shopId);
            List<ShopBaiduUrl> shopBaiduUrlList = shopBaiduUrlMapper.selectByCondition(condition);
            if (shopBaiduUrlList != null && shopBaiduUrlList.size() > 0) {
                ShopBaiduUrl recObj = null;

                if (branchId != null) {
                    for (ShopBaiduUrl temp : shopBaiduUrlList) {
                        if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2
                                && branchId.equals(temp.getBranchId())
                                ) {
                            recObj = temp;
                            break;
                        }
                    }
                }else {
                    for (ShopBaiduUrl temp : shopBaiduUrlList) {
                        if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2) {
                            recObj = temp;
                            break;
                        }
                    }
                }

                if (recObj == null) {
                    if (branchId != null) {
                        for (ShopBaiduUrl temp : shopBaiduUrlList) {
                            if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2) {
                                recObj = temp;
                                break;
                            }
                        }
                    }

                    if (recObj == null) {
                        return "";
                    }
                }

                String token = getAuth(recObj.getApiKey(), recObj.getSecurityKey());

                token = URLEncoder.encode(token);

                setKey(tokenKey + shopId + branchId, token, tokenExpireTime - 10000);
                setKey(baiduAppidKey + shopId + branchId, recObj.getAppid(), tokenExpireTime);

                return token;
            } else {
                return null;
            }
        } else {
            return tokenObj.toString();
        }

    }



    public Map<String, String> getBaiduTokenCur(Integer shopId, Integer branchId) {
        Map<String, String> tokenAppIdMap = new HashMap<>();

        Object tokenObj = getKey(tokenKeyCur + shopId + branchId);
        logger.info("getBaiduTokenCur,key={}, value={}", tokenKeyCur + shopId + branchId, tokenObj);

        if (tokenObj == null || branchId == null) {
            Condition condition = new Condition(ShopBaiduUrlCur.class);
            condition.or().andEqualTo("shopId", shopId);
            List<ShopBaiduUrlCur> shopBaiduUrlList = shopBaiduUrlCurMapper.selectByCondition(condition);
            if (shopBaiduUrlList != null && shopBaiduUrlList.size() > 0) {
                ShopBaiduUrlCur recObj = null;

                if (branchId != null) {
                    for (ShopBaiduUrlCur temp : shopBaiduUrlList) {
                        if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2
                                && branchId.equals(temp.getBranchId())
                                ) {
                            recObj = temp;
                            break;
                        }
                    }
                }else {
                    for (ShopBaiduUrlCur temp : shopBaiduUrlList) {
                        if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2) {
                            recObj = temp;
                            break;
                        }
                    }
                }

                if (recObj == null) {
                    if (branchId != null) {
                        for (ShopBaiduUrlCur temp : shopBaiduUrlList) {
                            if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2) {
                                recObj = temp;
                                break;
                            }
                        }
                    }

                    if (recObj == null) {
                        return null;
                    }
                }

                String token = getAuth(recObj.getApiKey(), recObj.getSecurityKey());

                token = URLEncoder.encode(token);

                setKey(tokenKeyCur + shopId + branchId, token, tokenExpireTime - 10000);
                setKey(baiduAppidKeyCur + shopId + branchId, recObj.getAppid(), tokenExpireTime);


                tokenAppIdMap.put("token", token);
                tokenAppIdMap.put("appId", recObj.getAppid());
                return tokenAppIdMap;
            } else {
                return null;
            }
        } else {

            tokenAppIdMap.put("token", tokenObj.toString());
            String appId = (String)getKey(baiduAppidKeyCur + shopId + branchId);
            tokenAppIdMap.put("appId", appId);
            return tokenAppIdMap;
        }

    }

    private Map<String, Integer> shopBranchCountMap = new HashMap<>();

    public Map<String, String> getBaiduTokenCurTempList(Integer shopId, Integer branchId) {
        Integer shopBranchBaiduCurCount = DataLoadService.shopBranchBaiduIdListMap.get(shopId + "_" + branchId);

        if (shopBranchBaiduCurCount != null && shopBranchBaiduCurCount > 1) {
            Integer shopBranchCount = shopBranchCountMap.get(shopId + "_" + branchId);

            if (shopBranchCount == null) {
                shopBranchCount = 1;
            }

            String baiduAppId = DataLoadService.shopBranchBaiduAppIdListMap.get(shopId + "_" + branchId + shopBranchCount);

            Object tempToken = getKey(tokenKeyCur + shopId + branchId + baiduAppId);

            if (tempToken == null) {
                getBaiduTokenCurList(shopId, branchId);
                tempToken = getKey(tokenKeyCur + shopId + branchId + baiduAppId);
            }


            if (shopBranchCount >= shopBranchBaiduCurCount) {
                shopBranchCount = 1;
            }else {
                shopBranchCount++;
            }

            shopBranchCountMap.put(shopId + "_" + branchId, shopBranchCount);

            if (tempToken != null) {
                Map<String, String> tokenAppIdMap = new HashMap<>();
                tokenAppIdMap.put("token", (String)tempToken);
                tokenAppIdMap.put("appId", baiduAppId);
                return tokenAppIdMap;
            }
        }

        Map<String, String> tokenAppIdMap = new HashMap<>();

        Object tokenObj = getKey(tokenKeyCur + shopId + branchId);
        logger.info("getBaiduTokenCur,key={}, value={}", tokenKeyCur + shopId + branchId, tokenObj);

        if (tokenObj == null || branchId == null) {
            Condition condition = new Condition(ShopBaiduUrlCur.class);
            condition.or().andEqualTo("shopId", shopId);
            List<ShopBaiduUrlCur> shopBaiduUrlList = shopBaiduUrlCurMapper.selectByCondition(condition);
            if (shopBaiduUrlList != null && shopBaiduUrlList.size() > 0) {
                ShopBaiduUrlCur recObj = null;

                if (branchId != null) {
                    for (ShopBaiduUrlCur temp : shopBaiduUrlList) {
                        if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2
                                && branchId.equals(temp.getBranchId())
                                ) {
                            recObj = temp;
                            break;
                        }
                    }
                }else {
                    for (ShopBaiduUrlCur temp : shopBaiduUrlList) {
                        if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2) {
                            recObj = temp;
                            break;
                        }
                    }
                }

                if (recObj == null) {
                    if (branchId != null) {
                        for (ShopBaiduUrlCur temp : shopBaiduUrlList) {
                            if (temp.getUrlType() != null && temp.getUrlType().intValue() == 2) {
                                recObj = temp;
                                break;
                            }
                        }
                    }

                    if (recObj == null) {
                        return null;
                    }
                }

                String token = getAuth(recObj.getApiKey(), recObj.getSecurityKey());

                token = URLEncoder.encode(token);

                setKey(tokenKeyCur + shopId + branchId, token, tokenExpireTime - 10000);
                setKey(baiduAppidKeyCur + shopId + branchId, recObj.getAppid(), tokenExpireTime);


                tokenAppIdMap.put("token", token);
                tokenAppIdMap.put("appId", recObj.getAppid());
                return tokenAppIdMap;
            } else {
                return null;
            }
        } else {

            tokenAppIdMap.put("token", tokenObj.toString());
            String appId = (String)getKey(baiduAppidKeyCur + shopId + branchId);
            tokenAppIdMap.put("appId", appId);
            return tokenAppIdMap;
        }

    }

    public List<Map<String, String>> getBaiduTokenCurList(Integer shopId, Integer branchId) {
        Condition condition = new Condition(ShopBaiduUrlCur.class);
        condition.or().andEqualTo("shopId", shopId)
                .andEqualTo("urlType", 2);
        List<ShopBaiduUrlCur> shopBaiduUrlList = shopBaiduUrlCurMapper.selectByCondition(condition);
        if (shopBaiduUrlList != null && shopBaiduUrlList.size() > 0) {
            if (branchId == null) {
                Condition branchCondition = new Condition(Branch.class);
                branchCondition.or().andEqualTo("shopId", shopId);

                List<Branch> branchList = branchMapper.selectByCondition(branchCondition);
                if (branchList != null && branchList.size() == 1) {
                    branchId = branchList.get(0).getBranchId();
                }
            }
            List<ShopBaiduUrlCur> shopBaiduUrlCurList = new ArrayList<>();

            if (branchId != null) {
                for (ShopBaiduUrlCur temp : shopBaiduUrlList) {
                    if (branchId.equals(temp.getBranchId())
                            ) {
                        shopBaiduUrlCurList.add(temp);
                    }
                }
            }else {
                for (ShopBaiduUrlCur temp : shopBaiduUrlList) {
                    shopBaiduUrlCurList.add(temp);
                }
            }

            if (shopBaiduUrlCurList.size() > 0) {
                List<Map<String, String>> mapList = new ArrayList<>();

                for (ShopBaiduUrlCur shopBaiduUrlCur : shopBaiduUrlCurList) {
                    Object token = getKey(tokenKeyCur + shopId + branchId + shopBaiduUrlCur.getAppid());
                    if (token == null) {
                        token = getAuth(shopBaiduUrlCur.getApiKey(), shopBaiduUrlCur.getSecurityKey());
                        token = URLEncoder.encode((String)token);
                        setKey(tokenKeyCur + shopId + branchId + shopBaiduUrlCur.getAppid(),
                                token.toString(), tokenExpireTime - 10000);
                        setKey(baiduAppidKeyCur + shopId + branchId + shopBaiduUrlCur.getAppid(),
                                shopBaiduUrlCur.getAppid(), tokenExpireTime);
                    }

                    Map<String, String> map = new HashMap<>();
                    map.put("token", (String)token);
                    map.put("appid", shopBaiduUrlCur.getAppid());

                    mapList.add(map);
                }

                return mapList;
            }

            return null;
        } else {
            return null;
        }

    }


    /**
     * {"x1":362,"y1":177,"x2":526,"y2":336,"score":1,"label":"红烧肉"},
     * {"x1":179,"y1":151,"x2":333,"y2":303,"score":1,"label":"海带丝"},
     * {"x1":50,"y1":72,"x2":576,"y2":405,"score":1,"label":"海带丝"}
     * @param shopId
     * @param fileBase64Content
     * @param filename
     * @param outputFilepath
     * @param uuidFileName
     * @param imgWidth
     * @param imgUrl
     * @param sourceImgOnInternet
     * @return
     * @throws Exception
     */
    public ProductRecResultVONewWithLocation searchImgNewWithLocation
            (Integer branchId, Integer shopId, String fileBase64Content,
              String filename, String outputFilepath,
              String uuidFileName, Integer[] imgWidth, String imgUrl, String sourceImgOnInternet) throws Exception {

        Date date = Calendar.getInstance().getTime();
        long startTime = date.getTime();
        logger.info("startTime1=" + startTime);

        String token = getBaiduToken(shopId, branchId);

        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token=" + token;

//        byte[] imgData = ImageBase64Util.netImageByte(filename);
//        byte[] imgData = com.binguo.api.webapi_tts.FileUtil.read(filename);
//        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(fileBase64Content, "UTF-8");

        String param = "image=" + imgParam + "&top_num=" + 5;

//        logger.info("param===" + param);

        try {
            List<ImgTag> imgTagList = new ArrayList<>();

            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = restTemplate.postForEntity(url, entity, String.class);


            logger.info(result.getBody());

            long endTime = System.currentTimeMillis();
            logger.info("endTime2=" + endTime + ", intelval=" + (endTime - startTime));



//            ThreadManager.executorService.submit(() -> {
            LogProductRec logProductRec = new LogProductRec();
            logProductRec.setFilepath(filename);
            logProductRec.setOutputFilepath(outputFilepath);
            logProductRec.setShopId(shopId);
            logProductRec.setImgSrcNetUrl(sourceImgOnInternet);
            logProductRec.setCreateTime(date);
            logProductRec.setRecResult(result.getBody());
            logProductRec.setImgResultNetUrl(imgUrl);
            logProductRecMapper.insert(logProductRec);
//            });

            long endTime22 = System.currentTimeMillis();
            logger.info("logProductRec=" + endTime + ",save intelval=" + (endTime22 - endTime));

            ProductImgModel productImgModel = new ProductImgModel();
            productImgModel.setProductOrderNo(uuidFileName);
            productImgModel.setShopId(shopId);
            productImgModel.setSourceFilename(filename);
            productImgModel.setUuidFileName(uuidFileName);
            productImgModel.setImgUrl(imgUrl);
            productImgModel.setCurIpAddress(ipAddress);
            productImgModel.setSourceImgOnInternet(sourceImgOnInternet);
            productImgModel.setItemList(new ArrayList<>());

            ProductRecResultVONewWithLocation productRecResultVO = null;

            if (result.getBody().contains("error_code")) {
                throw new ServiceException("识别失败");
            }
            BaiduSearchResult baiduSearchResult = JsonUtil.parse(result.getBody(), BaiduSearchResult.class);

            if (baiduSearchResult != null) {
                List<Result> searchResultList = baiduSearchResult.getResult();

                if (searchResultList != null && searchResultList.size() > 0) {
                    productRecResultVO = new ProductRecResultVONewWithLocation();
                    productRecResultVO.setProductList(new ArrayList<>());
                    productRecResultVO.setTotalFee(0l);
                    productRecResultVO.setRealFee(0l);

                    ThreadManager.executorService.submit(() -> {
                        addToProductImg(searchResultList, filename, shopId, uuidFileName, sourceImgOnInternet);
                    });

                    int seq = 1;

                    List<Result> needRemovedList = null;
                    for (Result temp : searchResultList) {
                        int x1 = temp.getLocation().getLeft();
                        int y1 = temp.getLocation().getTop();

                        int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                        int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();


                        for (Result compare : searchResultList) {
                            int x3 = compare.getLocation().getLeft();
                            int y3 = compare.getLocation().getTop();

                            int x4 = compare.getLocation().getLeft() + compare.getLocation().getWidth();
                            int y4 = compare.getLocation().getTop() + compare.getLocation().getHeight();


                            if (x1 < x3 && y1 < y3
                                    && x2 > x4 && y2 > y4
                                    ) {
                                logger.info("检测有图片包含: top=" + temp.getLocation().getTop());
                                if (needRemovedList == null) {
                                    needRemovedList = new ArrayList<>();
                                }
                                needRemovedList.add(temp);
                            }
                        }
                    }
                    for (Result temp : searchResultList) {
                        List<Dishes> dishesList = temp.getDishes();
                        if (dishesList != null && dishesList.size() > 0) {
                            double score = 0;
                            String shopProductId = null;
                            Set<String> shopProductIdList = new HashSet<>();
                            for (Dishes dishes : dishesList) {
                                if (!dishes.getBrief().contains("_")) {
                                    continue;
                                }
                                if (dishes.getScore() > score) {
                                    shopProductId = dishes.getBrief();
                                    score = dishes.getScore();
                                }
                                shopProductIdList.add(dishes.getBrief());
                            }

                            logger.info("score=" + score);

                            if (score < 0.3) {
                                continue;
                            }

                            /*if (temp.getLocation().getWidth() > 0.7 * imgWidth[0]
                                    && temp.getLocation().getHeight() > 0.7 * imgWidth[1]
                                    ) {
                                logger.info("getLocation().getWidth() > 0.7");
                                continue;
                            }*/

                            int x1 = temp.getLocation().getLeft();
                            int y1 = temp.getLocation().getTop();

                            int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                            int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();


                            /**
                             * 检测是否有图片包含
                             */
                            if (needRemovedList != null) {
                                boolean flag = false;
                                for (Result badResult : needRemovedList) {
                                    if (badResult.getLocation().getTop() == temp.getLocation().getTop()
                                            && badResult.getLocation().getWidth() == temp.getLocation().getWidth()
                                            && badResult.getLocation().getHeight() == temp.getLocation().getHeight()
                                            && badResult.getLocation().getLeft() == temp.getLocation().getLeft()
                                            ) {
                                        flag = true;
                                        break;
                                    }
                                }

                                if (flag) {
                                    logger.info("忽略检测有图片包含: top=" + temp.getLocation().getTop());
                                    continue;
                                }
                            }

                            ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                                    = new ProductRecResultDetailVONewWithLocation();

                            final Product[] product = new Product[1];

                            final Integer productId;
                            if (shopProductId.contains("_")) {
                                productId = Integer.valueOf(shopProductId.split("_")[1]);
                            } else {
                                productId = null;
                            }

                            if (score < 0.75) {
                                List<Integer> productIdList = new ArrayList<>();
                                shopProductIdList.stream().forEach(sp -> {
                                    productIdList.add(Integer.valueOf(sp.split("_")[1]));
                                });

                                List<ProductRecOthersVO> productRecResultVOList = new ArrayList<>();

                                if (DataLoadService.productMap != null) {
                                    for (Integer tempProductId : productIdList) {
                                        Product tempProduct = DataLoadService.productMap.get(tempProductId);
                                        if (tempProduct == null) {
                                            tempProduct = productMapper.selectByPrimaryKey(tempProductId);
                                        }
                                        ProductRecOthersVO recResultVO = new ProductRecOthersVO();
                                        recResultVO.setProductName(tempProduct.getName());
                                        recResultVO.setProductId(tempProduct.getId());
                                        recResultVO.setProductPrice(tempProduct.getPrice());
                                        recResultVO.setItemCount(1);

                                        productRecResultVOList.add(recResultVO);

                                        if (tempProduct.getId().equals(productId)) {
                                            product[0] = tempProduct;
                                        }
                                    }

                                    productRecResultVOList.sort(Comparator.comparing(ProductRecOthersVO::getProductPrice));
                                }else{
                                    String productIdListStr = org.apache.commons.lang3.StringUtils.join(productIdList.toArray(), ",");
                                    List<Product> productList = productMapper.selectByIds(productIdListStr);



                                    productList.stream().forEach(p -> {
                                        ProductRecOthersVO recResultVO = new ProductRecOthersVO();
                                        recResultVO.setProductName(p.getName());
                                        recResultVO.setProductPrice(p.getPrice());
                                        recResultVO.setProductId(p.getId());
                                        recResultVO.setItemCount(1);

                                        productRecResultVOList.add(recResultVO);

                                        if (p.getId().equals(productId)) {
                                            product[0] = p;
                                        }
                                    });
                                }

                                productRecResultDetailVO.setConfident(0);
                                productRecResultDetailVO.setOtherProductList(productRecResultVOList);
                            } else {
                                productRecResultDetailVO.setConfident(1);
                                product[0] = productMapper.selectByPrimaryKey(productId);
                            }



                            String label = product[0].getName();
//                            String label = product[0].getName() + "  " + PriceUtil.changeF2Y(product[0].getPrice()) + "元";

                            ImgTag imgTag = new ImgTag();
                            imgTag.setX1(x1);
                            imgTag.setY1(y1);
                            imgTag.setX2(x2);
                            imgTag.setY2(y2);
                            imgTag.setLabel(label);
                            if (score < 0.75) {
                                imgTag.setScore(0);
                            } else {
                                imgTag.setScore(1);
                            }
                            imgTagList.add(imgTag);

                            /**
                             * save ProductImgDetailModel
                             */
                            ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                            productImgDetailModel.setProductName(product[0].getName());
                            productImgDetailModel.setProductId(product[0].getId());
                            productImgDetailModel.setSeq(seq);
                            productImgDetailModel.setLeft(x1);
                            productImgDetailModel.setTop(y1);
                            productImgDetailModel.setWidth(temp.getLocation().getWidth());
                            productImgDetailModel.setHeight(temp.getLocation().getHeight());
                            productImgDetailModel.setScore(score);
                            productImgModel.getItemList().add(productImgDetailModel);
                            ///----end

                            productRecResultDetailVO.setX1(x1);
                            productRecResultDetailVO.setX2(x2);
                            productRecResultDetailVO.setY1(y1);
                            productRecResultDetailVO.setY2(y2);

                            productRecResultDetailVO.setProductName(product[0].getName());
                            productRecResultDetailVO.setProductId(product[0].getId());
                            productRecResultDetailVO.setProductPrice(product[0].getPrice());
                            productRecResultDetailVO.setItemCount(1);
                            productRecResultDetailVO.setSeq(seq);

                            productRecResultVO.getProductList().add(productRecResultDetailVO);
                            productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                                    + product[0].getPrice().longValue());

                            seq++;
                        }else {
                            //针对框出来不识别的情况
//                            Integer tempSeq = handleNotRecImg(filename, shopId, uuidFileName, temp, productRecResultVO, seq, productImgModel);
//                            if (tempSeq != null) {
//                                seq = tempSeq;
//                            }
                        }
                    }

                    ThreadManager.executorService.submit(() -> {
                        try {
                            setKey(productImgModel.getProductOrderNo(), productImgModel, 60 * 60 * 1000);
                            ProductImgJsonInfo productImgJsonInfo = new ProductImgJsonInfo();
                            productImgJsonInfo.setProductContent(JsonUtil.toJson(productImgModel));
                            productImgJsonInfo.setProductOrderNo(productImgModel.getProductOrderNo());

                            productImgJsonInfoMapper.insert(productImgJsonInfo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });

                    productRecResultVO.setRealFee(productRecResultVO.getTotalFee());
                    productRecResultVO.setProductCount(productRecResultVO.getProductList().size());

                }

                if (productRecResultVO == null) {
                    return null;
                }

                String imgJson = JsonUtil.toJson(imgTagList);

                logger.info("imgJson==" + imgJson);
                String temp = java.util.Base64.getEncoder().encodeToString(imgJson.getBytes());
                logger.info(temp);

                imgJson = URLEncoder.encode(temp);
                logger.info(imgJson);

                long endTime2 = System.currentTimeMillis();
                logger.info("endTime3=" + endTime + ", intelval=" + (endTime2 - endTime));

//                String drwaImgParam = "outputFilepath=" + outputFilepath + "&filename=" + filename + "&image=" + imgJson;
//
                String tempOutputFilepath = outputFilepath.replaceAll("/usr/local/nginx/html", "/data/html");
                String tempFilename = filename.replaceAll("/usr/local/nginx/html", "/data/html");

                String drwaImgParam = "outputFilepath=" + tempOutputFilepath + "&filename=" + tempFilename + "&image=" + imgJson;


                entity = new HttpEntity<>(drwaImgParam, DEFAULT_JSON_HEADER);

                ResponseEntity<String> drwaImgResult = restTemplate.postForEntity("http://"+recIp+":8082/hello2", entity, String.class);

                logger.info(drwaImgResult.getBody());


                long endTime3 = System.currentTimeMillis();
                logger.info("endTime4=" + endTime + ", intelval=" + (endTime3 - endTime2));

                if ("ok".equals(drwaImgResult.getBody())) {
                    return productRecResultVO;
                }

                logger.info(result.getBody());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public boolean errorExistErrorExist = true;

    /**
     * {"x1":362,"y1":177,"x2":526,"y2":336,"score":1,"label":"红烧肉"},
     * {"x1":179,"y1":151,"x2":333,"y2":303,"score":1,"label":"海带丝"},
     * {"x1":50,"y1":72,"x2":576,"y2":405,"score":1,"label":"海带丝"}
     * @param shopId
     * @param fileBase64Content
     * @param filename
     * @param outputFilepath
     * @param uuidFileName
     * @param imgUrl
     * @param sourceImgOnInternet
     * @param recType 1:纠正时的识别
     * @return
     * @throws Exception
     */
    public ProductRecResultVONewWithLocation searchImgNewWithLocationAndHuawei
            (Integer shopId, String fileBase64Content,
              String filename, String outputFilepath,
              String uuidFileName,
             String imgUrl, String sourceImgOnInternet, Integer branchId, Integer recType) throws Exception {

        Date date = Calendar.getInstance().getTime();
        long startTime = date.getTime();
        logger.info("开始识别:" + startTime);

        List<ProductYpRef> productYpRefList = null;
        if (DataLoadService.shopYpProductListMap != null) {
            productYpRefList = DataLoadService.shopYpProductListMap.get(shopId);
        }

        String token;
        if (recType != null && recType.equals(1)) {//纠正状态
            token = getBaiduToken(shopId, branchId);
        }else {
            token = getBaiduToken(shopId, branchId);
        }



        Future<String> baiduRecFuture = ThreadManager.executorService.submit((Callable) () ->
        {
            long baidurecStart = System.currentTimeMillis();


            String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token=" + token;

            String imgParam = URLEncoder.encode(fileBase64Content, "UTF-8");

            String param = "image=" + imgParam + "&top_num=" + 5;

            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = restTemplate.postForEntity(url, entity, String.class);

            logger.info(result.getBody());

            long endTime = System.currentTimeMillis();
            logger.info("百度识别完成=" + endTime + ",baidu rec intelval=" + (endTime - baidurecStart));

            return result.getBody();
        });


        RecResult huaRecResult = null;
        if (productYpRefList != null && productYpRefList.size() > 0) {
            logger.info("包含云澎菜品库商品: shopId:" + shopId + ", ipAddress=" + ipAddress);

            if (DataLoadService.useBaidu == 1) {
                Future<RecResult> easydlRecFuture = ThreadManager.executorService.submit((Callable) () ->
                        {
                            long huaweirecStart = System.currentTimeMillis();


//                            String drwaImgParam = "outputFilepath=" + uuidFileName + ".png&filename=http://182.254.215.43:8019/images/source/80/a5d5cadc-e026-4648-9061-9611da236d0e.png";
                            String drwaImgParam = "outputFilepath=" + uuidFileName + ".png&filename=" + sourceImgOnInternet;

                            HttpEntity entity = new HttpEntity<>(drwaImgParam, DEFAULT_JSON_HEADER);

                            logger.info("easydl param==" + drwaImgParam);

                            ResponseEntity<String> drwaImgResult = restTemplate.postForEntity("http://180.76.105.132:8099/hello", entity, String.class);

                            logger.info(drwaImgResult.getBody());

                            ResResult resResult = JsonUtil.parse(drwaImgResult.getBody(), ResResult.class);

                            RecResult result = new RecResult();

                            if (resResult.getRes() != null && resResult.getRes().size() > 0) {

                                result.setDetectionBoxes(new ArrayList<>());
                                result.setDetectionClasses(new ArrayList<>());
                                result.setDetectionScores(new ArrayList<>());

                                for (Res res : resResult.getRes()) {
                                    double x1 = res.getX1() * resResult.getW();
                                    double y1 = res.getY1() * resResult.getH();
                                    double x2 = res.getX2() * resResult.getW();
                                    double y2 = res.getY2() * resResult.getH();

                                    List<Double> location = new ArrayList<>();
                                    location.add(y1);
                                    location.add(x1);
                                    location.add(y2);
                                    location.add(x2);

                                    result.getDetectionBoxes().add(location);
                                    result.getDetectionScores().add(res.getConfidence());
                                    result.getDetectionClasses().add(res.getLabel());
                                }
                            }
                            long endTime = System.currentTimeMillis();
                            logger.info("百度easydl识别结果=" + JsonUtil.toJson(result));
                            logger.info("百度easydl识别完成=" + endTime + ",huawei rec intelval=" + (endTime - huaweirecStart));

                            return result;
                        }
                );
                try {

                    huaRecResult = easydlRecFuture.get();
                } catch (Exception e) {

                    logger.error(e.getMessage());
                }

            }/*else{
                String huaweiUrl = DataLoadService.huaweiUrl;
                Future<RecResult> huaweiRecFuture = ThreadManager.executorService.submit((Callable) () ->
                        {
                            long huaweirecStart = System.currentTimeMillis();
                            RecResult result = ImageSearchDemo.restPost(srcImgByte, huaweiUrl);

                            long endTime = System.currentTimeMillis();
                            logger.info("华为识别结果=" + JsonUtil.toJson(result));
                            logger.info("华为识别完成=" + endTime + ",huawei rec intelval=" + (endTime - huaweirecStart));

                            return result;
                        }
                );
                huaRecResult = huaweiRecFuture.get();
            }*/ else if (DataLoadService.useBaidu == 2) {//走本地识别流程
                String url = DataLoadService.shopLocalRecUrlmap.get(shopId);
                logger.info("url====={}", url);
                Future<RecResult> localRecFuture = ThreadManager.executorService.submit((Callable) () ->
                        {
                            long localrecStart = System.currentTimeMillis();

                            Map<String, String> param = new HashMap<>();
                            param.put("shopId", shopId + "");
//                            param.put("imgUrl", "http://182.254.215.43:8019/images/source/166/4a7fafa9-d665-4337-a88e-7b10f9b7b6b2.png");
                            param.put("imgUrl", sourceImgOnInternet);
                            String jsonParam = JsonUtil.toJson(param);

                            HttpEntity entity = new HttpEntity<>(jsonParam, DEFAULT_JSON_HEADER_UTF8);



                            ResponseEntity<String> recImgResult = new RestTemplate().postForEntity(url, entity, String.class);

                            try {
                                String resultStr = recImgResult.getBody();

//                                System.out.println(resultStr);
                                logger.info("local识别结果：{}", resultStr);
                                if (resultStr == null) {
                                    logger.info("本地模型识别无结果=");
                                    return null;
                                }
                                resultStr = resultStr.substring(resultStr.indexOf("results")-2);
                                ImgRecResult resResult = JsonUtil.parse(resultStr, ImgRecResult.class);


                                System.out.println(resResult.getNumber());

                                if (resResult.getNumber() > 0) {

                                    RecResult result = new RecResult();
                                    result.setDetectionBoxes(new ArrayList<>());
                                    result.setDetectionClasses(new ArrayList<>());
                                    result.setDetectionScores(new ArrayList<>());

                                    for (Results  res : resResult.getResults()) {
                                        int x1 = res.getLocation().getLeft();
                                        int y1 = res.getLocation().getTop();

                                        int x2 = res.getLocation().getLeft() + res.getLocation().getWidth();
                                        int y2 = res.getLocation().getTop() + res.getLocation().getHeight();


                                        List<Double> location = new ArrayList<>();
                                        location.add(Double.valueOf(y1));
                                        location.add(Double.valueOf(x1));
                                        location.add(Double.valueOf(y2));
                                        location.add(Double.valueOf(x2));

                                        result.getDetectionBoxes().add(location);
                                        result.getDetectionScores().add(res.getScore());
                                        result.getDetectionClasses().add(res.getName());
                                    }


                                    long endTime = System.currentTimeMillis();
                                    logger.info("本地模型识别结果=" + JsonUtil.toJson(result));
                                    logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));


                                    return result;
                                }else {
                                    long endTime = System.currentTimeMillis();
                                    logger.info("本地模型识别无结果");
                                    logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                logger.info("本地模型识别错误：{}", e.getMessage());
                            }


                            return null;

                        }
                );
                try {

                    huaRecResult = localRecFuture.get();
                } catch (Exception e) {

                    logger.error(e.getMessage());
                }
            }

        }
        String baiduRecResult = baiduRecFuture.get();

        long endRec = System.currentTimeMillis();
        logger.info("识别完成时间" + endRec +",interval:" + (endRec - startTime));

        BaiduSearchResult baiduSearchResult = null;
        try {
            baiduSearchResult = JsonUtil.parse(baiduRecResult, BaiduSearchResult.class);

        } catch (Exception e) {
            logger.info("error:" + e.getMessage());
        }


        final List<NeedReplacedProduct> needReplacedList;
        if (huaRecResult != null) {
            List<String> stringProductYpRefMap = null;
            if (DataLoadService.useBaidu == 1) {
                stringProductYpRefMap = DataLoadService.shopYpProductBaiduTagNameListMap.get(shopId);
            } else if (DataLoadService.useBaidu == 2) {
                stringProductYpRefMap = DataLoadService.shopYpProductSearchCodeListMap.get(shopId);
            }

            List<HuaweiProduct> huaweiProductList = new ArrayList<>();
            for (int i=0; i < huaRecResult.getDetectionClasses().size(); i++) {
                String detectName = huaRecResult.getDetectionClasses().get(i);

                if (stringProductYpRefMap!= null && stringProductYpRefMap.contains(detectName)) {
                    double score = huaRecResult.getDetectionScores().get(i);
                    if (score > DataLoadService.huaweiScore) {
                        List<Double> boxes = huaRecResult.getDetectionBoxes().get(i);

                        if (boxes.get(0) < 10 && boxes.get(1) < 10) {
                            continue;
                        }

                        int y1 = boxes.get(0).intValue();
                        int x1 = boxes.get(1).intValue();

                        int y2 = boxes.get(2).intValue();
                        int x2 = boxes.get(3).intValue();

                        //右上角坐标
                        int y11 = y1;
                        int x11 = x2;

                        boolean addFlag = true;

                        boolean needRemove = false;
                        HuaweiProduct needRemoveObj = null;
                        for (HuaweiProduct huaweiProduct : huaweiProductList) {
                            int y3 = huaweiProduct.getLocation().get(0).intValue();
                            int x3 = huaweiProduct.getLocation().get(1).intValue();

                            int y4 = huaweiProduct.getLocation().get(2).intValue();
                            int x4 = huaweiProduct.getLocation().get(3).intValue();

                            //右上角坐标
                            int y22 = y3;
                            int x22 = x4;

                            if (       ((x1 < (x3 + width) && x1 > (x3 - width))
                                    && (y1 < (y3 + width) && y1 > (y3 - width)))

                                    ||

                                    ((x2 < (x4 + width) && x2 > (x4 - width))
                                            && (y2 < (y4 + width) && y2 > (y4 - width)))

                                    ||

                                    ((x11 < (x22 + width) && x11 > (x22 - width))
                                            && (y11 < (y22 + width) && y11 > (y22 - width)))

                                    ) {

                                    if (score > huaweiProduct.getScore()) {
                                        addFlag = true;
                                        needRemove = true;
                                        needRemoveObj = huaweiProduct;
                                        break;
                                    }else {
                                        addFlag = false;
                                    }
                            }
                        }
                        if (needRemove) {
                            for (HuaweiProduct huaweiProduct : huaweiProductList) {
                                if (huaweiProduct.getProductId() == needRemoveObj.getProductId()
                                        && huaweiProduct.getScore() == needRemoveObj.getScore()
                                        ) {
                                    huaweiProductList.remove(huaweiProduct);
                                    break;
                                }
                            }
                        }

                        if (addFlag) {
                            ProductYpRef temp = null;
                            if (DataLoadService.useBaidu == 1) {
                                temp = DataLoadService.getProductYpRef(detectName, shopId, branchId);
                            } else if (DataLoadService.useBaidu == 2) {
                                temp = DataLoadService.getProductYpRefBySearchCode(detectName, shopId, branchId);
                            }
                            if (temp == null) {
                                continue;
                            }
                            HuaweiProduct huaweiProduct = new HuaweiProduct();
                            huaweiProduct.setProductId(temp.getProductId());
                            huaweiProduct.setProductName(temp.getProductName());
                            huaweiProduct.setLocation(boxes);
                            huaweiProduct.setScore(huaRecResult.getDetectionScores().get(i));
                            huaweiProductList.add(huaweiProduct);
                        }
                    }
                }
            }


            needReplacedList = new ArrayList<>();

            for (HuaweiProduct huaweiProduct : huaweiProductList) {
                int y1 = huaweiProduct.getLocation().get(0).intValue();
                int x1 = huaweiProduct.getLocation().get(1).intValue();

                int y2 = huaweiProduct.getLocation().get(2).intValue();
                int x2 = huaweiProduct.getLocation().get(3).intValue();

                //右上角坐标
                int y11 = y1;
                int x11 = x2;

                boolean addedFlag = false;
                if (baiduSearchResult != null) {
                    for (Result compare : baiduSearchResult.getResult()) {
                        int y3 = compare.getLocation().getTop();
                        int x3 = compare.getLocation().getLeft();

                        int x4 = compare.getLocation().getLeft() + compare.getLocation().getWidth();
                        int y4 = compare.getLocation().getTop() + compare.getLocation().getHeight();

                        //右上角坐标
                        int y22 = y3;
                        int x22 = x4;

                        if (       ((x1 < (x3 + width) && x1 > (x3 - width))
                                && (y1 < (y3 + width) && y1 > (y3 - width)))

                                ||

                                ((x2 < (x4 + width) && x2 > (x4 - width))
                                        && (y2 < (y4 + width) && y2 > (y4 - width)))

                                ||

                                ((x11 < (x22 + width) && x11 > (x22 - width))
                                        && (y11 < (y22 + width) && y11 > (y22 - width)))

                                ) {

                            List<Dishes> compareDishes = compare.getDishes();
                            if (compareDishes != null && compareDishes.size() > 0) {
                                if (huaweiProduct.getScore() < 0.98) {
                                    if (compareDishes.get(0).getScore() > 0.7) {
                                        addedFlag = true;
                                        continue;
                                    }
                                }
                            }
                            logger.info("检测到云澎菜品库商品,id:" + huaweiProduct.getProductId() +
                                    ",name=" + huaweiProduct.getProductName() + ",baiduTop:" + compare.getLocation().getTop());


                            NeedReplacedProduct needReplacedProduct = new NeedReplacedProduct();
                            needReplacedProduct.setHuaweiProduct(huaweiProduct);
                            needReplacedProduct.setBaiduResult(compare);
                            needReplacedProduct.setHandled(false);
                            needReplacedList.add(needReplacedProduct);

                            addedFlag = true;
                        }
                    }
                }

                if (!addedFlag) {
                    NeedReplacedProduct needReplacedProduct = new NeedReplacedProduct();
                    needReplacedProduct.setHuaweiProduct(huaweiProduct);
                    needReplacedProduct.setBaiduResult(null);
                    needReplacedProduct.setHandled(false);
                    needReplacedList.add(needReplacedProduct);
                }
            }
        }else {
            needReplacedList = null;
        }

        try {
            List<ImgTag> imgTagList = new ArrayList<>();

            ThreadManager.executorService.submit(() -> {
                LogProductRec logProductRec = new LogProductRec();
                logProductRec.setFilepath(filename);
                logProductRec.setOutputFilepath(outputFilepath);
                logProductRec.setShopId(shopId);
                logProductRec.setImgSrcNetUrl(sourceImgOnInternet);
                logProductRec.setCreateTime(date);
                logProductRec.setRecResult(baiduRecResult);
                logProductRec.setImgResultNetUrl(imgUrl);
                logProductRecMapper.insert(logProductRec);
            });

            long endTime22 = System.currentTimeMillis();
            logger.info("搜索比对云澎菜品库时间=" + endTime22 + ", intelval=" + (endTime22 - endRec));

            ProductImgModel productImgModel = new ProductImgModel();
            productImgModel.setProductOrderNo(uuidFileName);
            productImgModel.setShopId(shopId);
            productImgModel.setSourceFilename(filename);
            productImgModel.setUuidFileName(uuidFileName);
            productImgModel.setImgUrl(imgUrl);
            productImgModel.setCurIpAddress(ipAddress);
            productImgModel.setSourceImgOnInternet(sourceImgOnInternet);
            productImgModel.setItemList(new ArrayList<>());

            ProductRecResultVONewWithLocation productRecResultVO = null;

            /*if (baiduRecResult.contains("error_code")) {
                throw new ServiceException("识别失败");
            }*/


            if (baiduSearchResult != null || huaRecResult != null) {
                final List<Result> searchResultList;
                if (baiduSearchResult != null) {
                    searchResultList = baiduSearchResult.getResult();
                }else {
                    searchResultList = null;
                }

                if ((searchResultList != null && searchResultList.size() > 0)
                        || huaRecResult != null
                        ) {
                    productRecResultVO = new ProductRecResultVONewWithLocation();
                    productRecResultVO.setProductList(new ArrayList<>());
                    productRecResultVO.setTotalFee(0l);
                    productRecResultVO.setRealFee(0l);

                    ThreadManager.executorService.submit(() -> {
                        if (searchResultList != null) {
                            addToProductImgWithHuawei(searchResultList, filename,
                                    shopId, uuidFileName, sourceImgOnInternet, needReplacedList);
                        }
                    });

                    int seq = 1;

                    List<Result> needRemovedList = null;

                    if(searchResultList != null)
                    for (Result temp : searchResultList) {
                        int x1 = temp.getLocation().getLeft();
                        int y1 = temp.getLocation().getTop();

                        int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                        int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();


                        for (Result compare : searchResultList) {
                            int x3 = compare.getLocation().getLeft();
                            int y3 = compare.getLocation().getTop();

                            int x4 = compare.getLocation().getLeft() + compare.getLocation().getWidth();
                            int y4 = compare.getLocation().getTop() + compare.getLocation().getHeight();


                            if (x1 < x3 && y1 < y3
                                    && x2 > x4 && y2 > y4
                                    ) {
                                logger.info("检测有图片包含: top=" + temp.getLocation().getTop());
                                if (needRemovedList == null) {
                                    needRemovedList = new ArrayList<>();
                                }
                                if (!needRemovedList.contains(temp)) {
                                    needRemovedList.add(temp);
                                }
                            }
                        }

                        if(needReplacedList != null && needReplacedList.size() > 0)
                        for (NeedReplacedProduct needReplacedProduct : needReplacedList) {
                            HuaweiProduct huaweiProduct = needReplacedProduct.getHuaweiProduct();
                            int y3 = huaweiProduct.getLocation().get(0).intValue();
                            int x3 = huaweiProduct.getLocation().get(1).intValue();

                            int y4 = huaweiProduct.getLocation().get(2).intValue();
                            int x4 = huaweiProduct.getLocation().get(3).intValue();

                            if (x1 < x3 && y1 < y3
                                    && x2 > x4 && y2 > y4
                                    ) {
                                logger.info("本地识别检测有图片包含: top=" + temp.getLocation().getTop());
                                if (needRemovedList == null) {
                                    needRemovedList = new ArrayList<>();
                                }
                                needRemovedList.add(temp);
                            }
                        }
                    }

                    if(searchResultList != null){
                        boolean errorExist = false;
                        for (Result temp : searchResultList) {
                            List<Dishes> dishesList = temp.getDishes();
                            if (dishesList == null || dishesList.size() == 0) {
                                errorExist = true;
                                break;
                            }
                        }

                        if (errorExist) {
                            long errorExistStart = System.currentTimeMillis();
                            int index = 0;
                            List<Future<RecResult>> recFutureList = new ArrayList<>();
                            for (Result temp : searchResultList) {
                                NeedReplacedProduct needReplacedProduct = null;
                                if (needReplacedList != null) {
                                    for (NeedReplacedProduct tempNeedReplacedProduct : needReplacedList) {
                                        if (tempNeedReplacedProduct.getBaiduResult() != null) {
                                            if (tempNeedReplacedProduct.getBaiduResult().getLocation().getTop() == temp.getLocation().getTop()
                                                    && tempNeedReplacedProduct.getBaiduResult().getLocation().getWidth() == temp.getLocation().getWidth()
                                                    && tempNeedReplacedProduct.getBaiduResult().getLocation().getHeight() == temp.getLocation().getHeight()
                                                    && tempNeedReplacedProduct.getBaiduResult().getLocation().getLeft() == temp.getLocation().getLeft()
                                                    ) {
                                                needReplacedProduct = tempNeedReplacedProduct;
                                                tempNeedReplacedProduct.setHandled(true);

                                                break;
                                            }
                                        }
                                    }
                                }

                                ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                                        = new ProductRecResultDetailVONewWithLocation();

                                final Product[] product = new Product[1];

                                final Integer productId;

                                if (needReplacedProduct != null) {
                                    productId = needReplacedProduct.getHuaweiProduct().getProductId();
                                    double score = 0.9;
                                    productRecResultDetailVO.setConfident(1);

                                    int y1 = needReplacedProduct.getHuaweiProduct().getLocation().get(0).intValue();
                                    int x1 = needReplacedProduct.getHuaweiProduct().getLocation().get(1).intValue();

                                    int y2 = needReplacedProduct.getHuaweiProduct().getLocation().get(2).intValue();
                                    int x2 = needReplacedProduct.getHuaweiProduct().getLocation().get(3).intValue();


                                    if (x2 > x1) {
                                        temp.getLocation().setWidth(x2 - x1);
                                    }else {
                                        temp.getLocation().setWidth(x1 - x2);
                                    }
                                    if (y2 > y1) {
                                        temp.getLocation().setHeight(y2 - y1);
                                    }else {
                                        temp.getLocation().setHeight(y1 - y2);
                                    }

                                    productRecResultDetailVO.setConfident(1);
                                    product[0] = productMapper.selectByPrimaryKey(productId);

                                    String label = product[0].getName();

                                    ImgTag imgTag = new ImgTag();
                                    imgTag.setX1(x1);
                                    imgTag.setY1(y1);
                                    imgTag.setX2(x2);
                                    imgTag.setY2(y2);
                                    imgTag.setLabel(label);
                                    imgTag.setScore(1);
                                    imgTagList.add(imgTag);

                                    /**
                                     * save ProductImgDetailModel
                                     */
                                    ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                                    productImgDetailModel.setProductName(product[0].getName());
                                    productImgDetailModel.setProductId(product[0].getId());
                                    productImgDetailModel.setSeq(seq);
                                    productImgDetailModel.setLeft(x1);
                                    productImgDetailModel.setTop(y1);
                                    productImgDetailModel.setWidth(temp.getLocation().getWidth());
                                    productImgDetailModel.setHeight(temp.getLocation().getHeight());
                                    productImgDetailModel.setScore(score);
                                    productImgModel.getItemList().add(productImgDetailModel);
                                    ///----end

                                    productRecResultDetailVO.setX1(x1);
                                    productRecResultDetailVO.setX2(x2);
                                    productRecResultDetailVO.setY1(y1);
                                    productRecResultDetailVO.setY2(y2);

                                    productRecResultDetailVO.setProductName(product[0].getName());
                                    productRecResultDetailVO.setProductId(product[0].getId());
                                    productRecResultDetailVO.setProductPrice(product[0].getPrice());
                                    productRecResultDetailVO.setItemCount(1);
                                    productRecResultDetailVO.setSeq(seq);

                                    productRecResultVO.getProductList().add(productRecResultDetailVO);
                                    productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                                            + product[0].getPrice().longValue());

                                }else{
                                    //针对框出来不识别的情况
                                    logger.info("======框出来不识别:{}, {}, {}, {}", temp.getLocation().getTop(),
                                            temp.getLocation().getLeft(), temp.getLocation().getWidth(), temp.getLocation().getHeight());


                                    Integer tempSeq = seq;
                                    Integer tempIndex = index;

                                    ProductRecResultVONewWithLocation tempProductRecResultVO = productRecResultVO;
                                    Future<RecResult> localRecFuture = ThreadManager.executorService.submit((Callable) () ->
                                    {
                                        long reRecStart = System.currentTimeMillis();
                                        handleNotRecImg(filename, shopId, uuidFileName,
                                                temp, tempProductRecResultVO, tempSeq,
                                                productImgModel, imgTagList, branchId, tempIndex, token, recType);
                                        long reRecEnd = System.currentTimeMillis();
                                        logger.info("======框出来重新识别时间:{}, tempIndex:{}", reRecEnd - reRecStart, tempIndex);
                                        return null;
                                    });

                                    recFutureList.add(localRecFuture);
                                }


                                index++;

                                seq++;
                            }

                            for (Future<RecResult> recResultFuture : recFutureList) {
                                recResultFuture.get();
                            }
                            long errorExistEnd = System.currentTimeMillis();

                            logger.info("======框不出来重新识别时间:{}", errorExistEnd - errorExistStart);
                        }else{
                            for (Result temp : searchResultList) {
                                List<Dishes> dishesList = temp.getDishes();
                                if (dishesList != null && dishesList.size() > 0) {
                                    double score = 0;
                                    String shopProductId = null;
                                    Set<String> shopProductIdList = new HashSet<>();
                                    for (Dishes dishes : dishesList) {
                                        if (!dishes.getBrief().contains("_")) {
                                            continue;
                                        }
                                        if (dishes.getScore() > score) {
                                            shopProductId = dishes.getBrief();
                                            score = dishes.getScore();
                                        }
                                        shopProductIdList.add(dishes.getBrief());
                                    }

                                    logger.info("score=" + score);

                                    if (score < 0.3) {
                                        continue;
                                    }

                                    int x1 = temp.getLocation().getLeft();
                                    int y1 = temp.getLocation().getTop();

                                    int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                                    int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();


                                    /**
                                     * 检测是否有图片包含
                                     */
                                    if (needRemovedList != null) {
                                        boolean flag = false;
                                        for (Result badResult : needRemovedList) {
                                            if (badResult.getLocation().getTop() == temp.getLocation().getTop()
                                                    && badResult.getLocation().getWidth() == temp.getLocation().getWidth()
                                                    && badResult.getLocation().getHeight() == temp.getLocation().getHeight()
                                                    && badResult.getLocation().getLeft() == temp.getLocation().getLeft()
                                                    ) {
                                                flag = true;
                                                break;
                                            }
                                        }

                                        if (flag) {
                                            logger.info("忽略检测有图片包含: top=" + temp.getLocation().getTop());
                                            continue;
                                        }
                                    }

                                    if (temp.getLocation().getWidth() > 900 && temp.getLocation().getHeight() > 600
                                            ) {
                                        logger.info("检测图片 宽高过大，width=" + temp.getLocation().getWidth());
                                        continue;
                                    }

                                    NeedReplacedProduct needReplacedProduct = null;
                                    if (needReplacedList != null) {

                                        for (NeedReplacedProduct tempNeedReplacedProduct : needReplacedList) {
                                            if (tempNeedReplacedProduct.getBaiduResult() != null) {
                                                if (tempNeedReplacedProduct.getBaiduResult().getLocation().getTop() == temp.getLocation().getTop()
                                                        && tempNeedReplacedProduct.getBaiduResult().getLocation().getWidth() == temp.getLocation().getWidth()
                                                        && tempNeedReplacedProduct.getBaiduResult().getLocation().getHeight() == temp.getLocation().getHeight()
                                                        && tempNeedReplacedProduct.getBaiduResult().getLocation().getLeft() == temp.getLocation().getLeft()
                                                        ) {
                                                    tempNeedReplacedProduct.setHandled(true);
                                                    needReplacedProduct = tempNeedReplacedProduct;

                                                    break;
                                                }
                                            }
                                        }
                                    }

                                    ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                                            = new ProductRecResultDetailVONewWithLocation();

                                    final Product[] product = new Product[1];

                                    final Integer productId;

                                    if (needReplacedProduct != null) {
                                        productId = needReplacedProduct.getHuaweiProduct().getProductId();
                                        score = 0.9;
                                        productRecResultDetailVO.setConfident(1);

                                        y1 = needReplacedProduct.getHuaweiProduct().getLocation().get(0).intValue();
                                        x1 = needReplacedProduct.getHuaweiProduct().getLocation().get(1).intValue();

                                        y2 = needReplacedProduct.getHuaweiProduct().getLocation().get(2).intValue();
                                        x2 = needReplacedProduct.getHuaweiProduct().getLocation().get(3).intValue();


                                        if (x2 > x1) {
                                            temp.getLocation().setWidth(x2 - x1);
                                        }else {
                                            temp.getLocation().setWidth(x1 - x2);
                                        }
                                        if (y2 > y1) {
                                            temp.getLocation().setHeight(y2 - y1);
                                        }else {
                                            temp.getLocation().setHeight(y1 - y2);
                                        }
                                    }else{
                                        if (shopProductId.contains("_")) {
                                            productId = Integer.valueOf(shopProductId.split("_")[1]);
                                        } else {
                                            productId = null;
                                        }
                                    }

                                    if (score < 0.75) {
                                        List<Integer> productIdList = new ArrayList<>();
                                        shopProductIdList.stream().forEach(sp -> {
                                            productIdList.add(Integer.valueOf(sp.split("_")[1]));
                                        });

                                        List<ProductRecOthersVO> productRecResultVOList = new ArrayList<>();

                                        if (DataLoadService.productMap != null) {
                                            for (Integer tempProductId : productIdList) {
                                                Product tempProduct = DataLoadService.productMap.get(tempProductId);
                                                if (tempProduct == null) {
                                                    tempProduct = productMapper.selectByPrimaryKey(tempProductId);
                                                }
                                                ProductRecOthersVO recResultVO = new ProductRecOthersVO();
                                                recResultVO.setProductName(tempProduct.getName());
                                                recResultVO.setProductPrice(tempProduct.getPrice());
                                                recResultVO.setProductId(tempProduct.getId());
                                                recResultVO.setItemCount(1);

                                                productRecResultVOList.add(recResultVO);

                                                if (tempProduct.getId().equals(productId)) {
                                                    product[0] = tempProduct;
                                                }
                                            }

                                            productRecResultVOList.sort(Comparator.comparing(ProductRecOthersVO::getProductPrice));
                                        }else{
                                            String productIdListStr = org.apache.commons.lang3.StringUtils.join(productIdList.toArray(), ",");
                                            List<Product> productList = productMapper.selectByIds(productIdListStr);



                                            productList.stream().forEach(p -> {
                                                ProductRecOthersVO recResultVO = new ProductRecOthersVO();
                                                recResultVO.setProductName(p.getName());
                                                recResultVO.setProductPrice(p.getPrice());
                                                recResultVO.setItemCount(1);
                                                recResultVO.setProductId(p.getId());

                                                productRecResultVOList.add(recResultVO);

                                                if (p.getId().equals(productId)) {
                                                    product[0] = p;
                                                }
                                            });
                                        }

                                        productRecResultDetailVO.setConfident(0);
                                        productRecResultDetailVO.setOtherProductList(productRecResultVOList);
                                    } else {
                                        productRecResultDetailVO.setConfident(1);
                                        product[0] = productMapper.selectByPrimaryKey(productId);
                                    }



                                    String label = product[0].getName();
//                            String label = product[0].getName() + "  " + PriceUtil.changeF2Y(product[0].getPrice()) + "元";

                                    ImgTag imgTag = new ImgTag();
                                    imgTag.setX1(x1);
                                    imgTag.setY1(y1);
                                    imgTag.setX2(x2);
                                    imgTag.setY2(y2);
                                    imgTag.setLabel(label);
                                    if (score < 0.75) {
                                        imgTag.setScore(0);
                                    } else {
                                        imgTag.setScore(1);
                                    }
                                    imgTagList.add(imgTag);

                                    /**
                                     * save ProductImgDetailModel
                                     */
                                    ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                                    productImgDetailModel.setProductName(product[0].getName());
                                    productImgDetailModel.setProductId(product[0].getId());
                                    productImgDetailModel.setSeq(seq);
                                    productImgDetailModel.setLeft(x1);
                                    productImgDetailModel.setTop(y1);
                                    productImgDetailModel.setWidth(temp.getLocation().getWidth());
                                    productImgDetailModel.setHeight(temp.getLocation().getHeight());
                                    productImgDetailModel.setScore(score);
                                    productImgModel.getItemList().add(productImgDetailModel);
                                    ///----end

                                    productRecResultDetailVO.setX1(x1);
                                    productRecResultDetailVO.setX2(x2);
                                    productRecResultDetailVO.setY1(y1);
                                    productRecResultDetailVO.setY2(y2);

                                    productRecResultDetailVO.setProductName(product[0].getName());
                                    productRecResultDetailVO.setProductId(product[0].getId());
                                    productRecResultDetailVO.setProductPrice(product[0].getPrice());
                                    productRecResultDetailVO.setItemCount(1);
                                    productRecResultDetailVO.setSeq(seq);

                                    productRecResultVO.getProductList().add(productRecResultDetailVO);
                                    productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                                            + product[0].getPrice().longValue());

                                    seq++;
                                }
                            }
                        }
                    }


                    if (needReplacedList != null) {
                        for (NeedReplacedProduct needReplacedProduct : needReplacedList) {
                            if (!needReplacedProduct.isHandled()) {
                                Product product = productMapper.selectByPrimaryKey(needReplacedProduct.getHuaweiProduct().getProductId());

                                String label = needReplacedProduct.getHuaweiProduct().getProductName();

                                int y1 = needReplacedProduct.getHuaweiProduct().getLocation().get(0).intValue();
                                int x1 = needReplacedProduct.getHuaweiProduct().getLocation().get(1).intValue();

                                int y2 = needReplacedProduct.getHuaweiProduct().getLocation().get(2).intValue();
                                int x2 = needReplacedProduct.getHuaweiProduct().getLocation().get(3).intValue();

                                ImgTag imgTag = new ImgTag();
                                imgTag.setX1(x1);
                                imgTag.setY1(y1);
                                imgTag.setX2(x2);
                                imgTag.setY2(y2);
                                imgTag.setLabel(label);
                                imgTag.setScore(1);
                                imgTagList.add(imgTag);



                                /**
                                 * save ProductImgDetailModel
                                 */
                                ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                                productImgDetailModel.setProductName(needReplacedProduct.getHuaweiProduct().getProductName());
                                productImgDetailModel.setProductId(needReplacedProduct.getHuaweiProduct().getProductId());
                                productImgDetailModel.setSeq(seq);
                                productImgDetailModel.setLeft(x1);
                                productImgDetailModel.setTop(y1);
                                if (x2 > x1) {
                                    productImgDetailModel.setWidth(x2 - x1);
                                }else {
                                    productImgDetailModel.setWidth(x1 - x2);
                                }

                                if (y2 > y1) {
                                    productImgDetailModel.setHeight(y2 - y1);
                                }else {
                                    productImgDetailModel.setHeight(y1 - y2);
                                }
                                productImgDetailModel.setScore(1);

                                productImgModel.getItemList().add(productImgDetailModel);
                                ///----end

                                ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                                        = new ProductRecResultDetailVONewWithLocation();

                                productRecResultDetailVO.setX1(x1);
                                productRecResultDetailVO.setX2(x2);
                                productRecResultDetailVO.setY1(y1);
                                productRecResultDetailVO.setY2(y2);
                                productRecResultDetailVO.setConfident(1);

                                productRecResultDetailVO.setProductName(needReplacedProduct.getHuaweiProduct().getProductName());
                                productRecResultDetailVO.setProductId(needReplacedProduct.getHuaweiProduct().getProductId());

                                productRecResultDetailVO.setProductPrice(product.getPrice());
                                productRecResultDetailVO.setItemCount(1);
                                productRecResultDetailVO.setSeq(seq);

                                productRecResultVO.getProductList().add(productRecResultDetailVO);
                                productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                                        + product.getPrice().longValue());

                                seq++;
                            }
                        }
                    }

                    ThreadManager.executorService.submit(() -> {
                        try {
                            setKey(productImgModel.getProductOrderNo(), productImgModel, 60 * 60 * 1000);
                            ProductImgJsonInfo productImgJsonInfo = new ProductImgJsonInfo();
                            productImgJsonInfo.setProductContent(JsonUtil.toJson(productImgModel));
                            productImgJsonInfo.setProductOrderNo(productImgModel.getProductOrderNo());

                            productImgJsonInfoMapper.insert(productImgJsonInfo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });

                    productRecResultVO.setRealFee(productRecResultVO.getTotalFee());
                    productRecResultVO.setProductCount(productRecResultVO.getProductList().size());

                }

                if (productRecResultVO == null) {
                    return null;
                }

                String imgJson = JsonUtil.toJson(imgTagList);

                logger.info("imgJson==" + imgJson);
                String temp = java.util.Base64.getEncoder().encodeToString(imgJson.getBytes());
                logger.info(temp);

                imgJson = URLEncoder.encode(temp);
                logger.info(imgJson);

                long endTime2 = System.currentTimeMillis();
                logger.info("endTime3=" + endTime2 + ", intelval=" + (endTime2 - startTime));

//                String drwaImgParam = "outputFilepath=" + outputFilepath + "&filename=" + filename + "&image=" + imgJson;

                String tempOutputFilepath = outputFilepath.replaceAll("/usr/local/nginx/html", "/data/html");
                String tempFilename = filename.replaceAll("/usr/local/nginx/html", "/data/html");

                String drwaImgParam = "outputFilepath=" + tempOutputFilepath + "&filename=" + tempFilename + "&image=" + imgJson;

                HttpEntity entity = new HttpEntity<>(drwaImgParam, DEFAULT_JSON_HEADER);

                ResponseEntity<String> drwaImgResult = restTemplate.postForEntity("http://"+recIp+":8082/hello2", entity, String.class);

                logger.info(drwaImgResult.getBody());


                long endTime3 = System.currentTimeMillis();
                logger.info("endTime4=" + endTime3 + ", intelval=" + (endTime3 - endTime2));

                if ("ok".equals(drwaImgResult.getBody())) {
                    return productRecResultVO;
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Resource
    private ShopBaiduUrlCurMapper shopBaiduUrlCurMapper;

    public ProductRecResultVONewWithLocation search(Integer shopId, String fileBase64Content,
             String filename, String outputFilepath,
             String uuidFileName,
             String imgUrl, String sourceImgOnInternet, Integer branchId, Integer recType,
                                                    Integer imgWidth
                                                    ) throws Exception {

        Date date = Calendar.getInstance().getTime();
        long startTime = date.getTime();
        logger.info("开始识别:" + startTime);

        List<ProductYpRef> productYpRefList = null;
        if (DataLoadService.shopYpProductListMap != null) {
            productYpRefList = DataLoadService.shopYpProductListMap.get(shopId);
        }

        String token;
        boolean useMasterDb = false;

        int width = 30;
        if (imgWidth != null && imgWidth > 1000) {
            width = 60;
        }

        if (recType != null && recType.equals(1)) {
            token = getBaiduToken(shopId, branchId);
            useMasterDb = true;
        }else {
            if(DataLoadService.shopBaiduUrlCurListMap.get(shopId) != null){
                Map<String, String> tokenMap = getBaiduTokenCur(shopId, branchId);
                token = tokenMap.get("token");

                if (token == null) {
                    token = getBaiduToken(shopId, branchId);
                    useMasterDb = true;
                }
            }else {
                token = getBaiduToken(shopId, branchId);
            }
        }

        String tempToken = token;

        Future<String> baiduRecFuture = ThreadManager.executorService.submit((Callable) () ->
        {
            long baidurecStart = System.currentTimeMillis();


            String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token=" + tempToken;

            String imgParam = URLEncoder.encode(fileBase64Content, "UTF-8");

            String param = "image=" + imgParam + "&top_num=" + 5;

            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = restTemplate.postForEntity(url, entity, String.class);

            logger.info(result.getBody());

            long endTime = System.currentTimeMillis();
            logger.info("百度识别完成=" + endTime + ",baidu rec intelval=" + (endTime - baidurecStart));

            return result.getBody();
        });


        RecResult huaRecResult = null;
        if (productYpRefList != null && productYpRefList.size() > 0) {
            logger.info("包含云澎菜品库商品: shopId:" + shopId + ", ipAddress=" + ipAddress);

            if (DataLoadService.useBaidu == 1) {
                Future<RecResult> easydlRecFuture = ThreadManager.executorService.submit((Callable) () ->
                        {
                            long huaweirecStart = System.currentTimeMillis();


//                            String drwaImgParam = "outputFilepath=" + uuidFileName + ".png&filename=http://182.254.215.43:8019/images/source/80/a5d5cadc-e026-4648-9061-9611da236d0e.png";
                            String drwaImgParam = "outputFilepath=" + uuidFileName + ".png&filename=" + sourceImgOnInternet;

                            HttpEntity entity = new HttpEntity<>(drwaImgParam, DEFAULT_JSON_HEADER);

                            logger.info("easydl param==" + drwaImgParam);

                            ResponseEntity<String> drwaImgResult = restTemplate.postForEntity("http://180.76.105.132:8099/hello", entity, String.class);

                            logger.info(drwaImgResult.getBody());

                            ResResult resResult = JsonUtil.parse(drwaImgResult.getBody(), ResResult.class);

                            RecResult result = new RecResult();

                            if (resResult.getRes() != null && resResult.getRes().size() > 0) {

                                result.setDetectionBoxes(new ArrayList<>());
                                result.setDetectionClasses(new ArrayList<>());
                                result.setDetectionScores(new ArrayList<>());

                                for (Res res : resResult.getRes()) {
                                    double x1 = res.getX1() * resResult.getW();
                                    double y1 = res.getY1() * resResult.getH();
                                    double x2 = res.getX2() * resResult.getW();
                                    double y2 = res.getY2() * resResult.getH();

                                    List<Double> location = new ArrayList<>();
                                    location.add(y1);
                                    location.add(x1);
                                    location.add(y2);
                                    location.add(x2);

                                    result.getDetectionBoxes().add(location);
                                    result.getDetectionScores().add(res.getConfidence());
                                    result.getDetectionClasses().add(res.getLabel());
                                }
                            }
                            long endTime = System.currentTimeMillis();
                            logger.info("百度easydl识别结果=" + JsonUtil.toJson(result));
                            logger.info("百度easydl识别完成=" + endTime + ",huawei rec intelval=" + (endTime - huaweirecStart));

                            return result;
                        }
                );
                try {

                    huaRecResult = easydlRecFuture.get();
                } catch (Exception e) {

                    logger.error(e.getMessage());
                }

            }/*else{
                String huaweiUrl = DataLoadService.huaweiUrl;
                Future<RecResult> huaweiRecFuture = ThreadManager.executorService.submit((Callable) () ->
                        {
                            long huaweirecStart = System.currentTimeMillis();
                            RecResult result = ImageSearchDemo.restPost(srcImgByte, huaweiUrl);

                            long endTime = System.currentTimeMillis();
                            logger.info("华为识别结果=" + JsonUtil.toJson(result));
                            logger.info("华为识别完成=" + endTime + ",huawei rec intelval=" + (endTime - huaweirecStart));

                            return result;
                        }
                );
                huaRecResult = huaweiRecFuture.get();
            }*/ else if (DataLoadService.useBaidu == 2) {//走本地识别流程
                String url = DataLoadService.shopLocalRecUrlmap.get(shopId);
                logger.info("url====={}", url);
                Future<RecResult> localRecFuture = ThreadManager.executorService.submit((Callable) () ->
                        {
                            long localrecStart = System.currentTimeMillis();

                            Map<String, String> param = new HashMap<>();
                            param.put("shopId", shopId + "");
//                            param.put("imgUrl", "http://binguoai.com:8019/images/source/80/33b211dd-fa14-4632-b55c-030eb45e3099.png");
                            param.put("imgUrl", sourceImgOnInternet);
                            String jsonParam = JsonUtil.toJson(param);

                            HttpEntity entity = new HttpEntity<>(jsonParam, DEFAULT_JSON_HEADER_UTF8);



                            ResponseEntity<String> recImgResult = new RestTemplate().postForEntity(url, entity, String.class);

                            try {
                                String resultStr = recImgResult.getBody();

                                System.out.println(resultStr);
                                logger.info("local识别结果：{}", resultStr);
                                if (resultStr == null) {
                                    logger.info("本地模型识别无结果=");
                                    return null;
                                }
                                resultStr = resultStr.substring(resultStr.indexOf("results")-2);
                                ImgRecResult resResult = JsonUtil.parse(resultStr, ImgRecResult.class);


                                System.out.println(resResult.getNumber());

                                if (resResult.getNumber() > 0) {

                                    RecResult result = new RecResult();
                                    result.setDetectionBoxes(new ArrayList<>());
                                    result.setDetectionClasses(new ArrayList<>());
                                    result.setDetectionScores(new ArrayList<>());

                                    for (Results  res : resResult.getResults()) {
                                        int x1 = res.getLocation().getLeft();
                                        int y1 = res.getLocation().getTop();

                                        int x2 = res.getLocation().getLeft() + res.getLocation().getWidth();
                                        int y2 = res.getLocation().getTop() + res.getLocation().getHeight();


                                        List<Double> location = new ArrayList<>();
                                        location.add(Double.valueOf(y1));
                                        location.add(Double.valueOf(x1));
                                        location.add(Double.valueOf(y2));
                                        location.add(Double.valueOf(x2));

                                        result.getDetectionBoxes().add(location);
                                        result.getDetectionScores().add(res.getScore());
                                        result.getDetectionClasses().add(res.getName());
                                    }


                                    long endTime = System.currentTimeMillis();
                                    logger.info("本地模型识别结果=" + JsonUtil.toJson(result));
                                    logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));


                                    return result;
                                }else {
                                    long endTime = System.currentTimeMillis();
                                    logger.info("本地模型识别无结果");
                                    logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                logger.info("本地模型识别错误：{}", e.getMessage());
                            }


                            return null;

                        }
                );
                try {

                    huaRecResult = localRecFuture.get();
                } catch (Exception e) {

                    logger.error(e.getMessage());
                }
            }

        }
        String baiduRecResult = baiduRecFuture.get();

        long endRec = System.currentTimeMillis();
        logger.info("识别完成时间" + endRec +",interval:" + (endRec - startTime));

        BaiduSearchResult baiduSearchResult = null;
        try {
            baiduSearchResult = JsonUtil.parse(baiduRecResult, BaiduSearchResult.class);

        } catch (Exception e) {
            logger.info("error:" + e.getMessage());
        }


        final List<NeedReplacedProduct> needReplacedList;
        if (huaRecResult != null) {
            List<String> stringProductYpRefMap = null;
            if (DataLoadService.useBaidu == 1) {
                stringProductYpRefMap = DataLoadService.shopYpProductBaiduTagNameListMap.get(shopId);
            } else if (DataLoadService.useBaidu == 2) {
                stringProductYpRefMap = DataLoadService.shopYpProductSearchCodeListMap.get(shopId);
            }

            List<HuaweiProduct> huaweiProductList = new ArrayList<>();
            for (int i=0; i < huaRecResult.getDetectionClasses().size(); i++) {
                String detectName = huaRecResult.getDetectionClasses().get(i);

                if (stringProductYpRefMap!= null && stringProductYpRefMap.contains(detectName)) {
                    double score = huaRecResult.getDetectionScores().get(i);
                    if (score > DataLoadService.huaweiScore) {
                        List<Double> boxes = huaRecResult.getDetectionBoxes().get(i);

                        if (boxes.get(0) < 10 && boxes.get(1) < 10) {
                            continue;
                        }

                        int y1 = boxes.get(0).intValue();
                        int x1 = boxes.get(1).intValue();

                        int y2 = boxes.get(2).intValue();
                        int x2 = boxes.get(3).intValue();

                        //右上角坐标
                        int y11 = y1;
                        int x11 = x2;

                        boolean addFlag = true;

                        boolean needRemove = false;
                        HuaweiProduct needRemoveObj = null;
                        for (HuaweiProduct huaweiProduct : huaweiProductList) {
                            int y3 = huaweiProduct.getLocation().get(0).intValue();
                            int x3 = huaweiProduct.getLocation().get(1).intValue();

                            int y4 = huaweiProduct.getLocation().get(2).intValue();
                            int x4 = huaweiProduct.getLocation().get(3).intValue();

                            //右上角坐标
                            int y22 = y3;
                            int x22 = x4;

                            if (       ((x1 < (x3 + width) && x1 > (x3 - width))
                                    && (y1 < (y3 + width) && y1 > (y3 - width)))

                                    ||

                                    ((x2 < (x4 + width) && x2 > (x4 - width))
                                            && (y2 < (y4 + width) && y2 > (y4 - width)))

                                    ||

                                    ((x11 < (x22 + width) && x11 > (x22 - width))
                                            && (y11 < (y22 + width) && y11 > (y22 - width)))

                                    ) {

                                    if (score > huaweiProduct.getScore()) {
                                        addFlag = true;
                                        needRemove = true;
                                        needRemoveObj = huaweiProduct;
                                        break;
                                    }else {
                                        addFlag = false;
                                    }
                            }
                        }
                        if (needRemove) {
                            for (HuaweiProduct huaweiProduct : huaweiProductList) {
                                if (huaweiProduct.getProductId() == needRemoveObj.getProductId()
                                        && huaweiProduct.getScore() == needRemoveObj.getScore()
                                        ) {
                                    huaweiProductList.remove(huaweiProduct);
                                    break;
                                }
                            }
                        }

                        if (addFlag) {
                            ProductYpRef temp = null;
                            if (DataLoadService.useBaidu == 1) {
                                temp = DataLoadService.getProductYpRef(detectName, shopId, branchId);
                            } else if (DataLoadService.useBaidu == 2) {
                                temp = DataLoadService.getProductYpRefBySearchCode(detectName, shopId, branchId);
                            }
                            if (temp == null) {
                                continue;
                            }
                            HuaweiProduct huaweiProduct = new HuaweiProduct();
                            huaweiProduct.setProductId(temp.getProductId());
                            huaweiProduct.setProductName(temp.getProductName());
                            huaweiProduct.setLocation(boxes);
                            huaweiProduct.setScore(huaRecResult.getDetectionScores().get(i));
                            huaweiProductList.add(huaweiProduct);
                        }
                    }
                }
            }


            needReplacedList = new ArrayList<>();

            for (HuaweiProduct huaweiProduct : huaweiProductList) {
                int y1 = huaweiProduct.getLocation().get(0).intValue();
                int x1 = huaweiProduct.getLocation().get(1).intValue();

                int y2 = huaweiProduct.getLocation().get(2).intValue();
                int x2 = huaweiProduct.getLocation().get(3).intValue();

                //右上角坐标
                int y11 = y1;
                int x11 = x2;

                boolean addedFlag = false;
                if (baiduSearchResult != null) {
                    for (Result compare : baiduSearchResult.getResult()) {
                        int y3 = compare.getLocation().getTop();
                        int x3 = compare.getLocation().getLeft();

                        int x4 = compare.getLocation().getLeft() + compare.getLocation().getWidth();
                        int y4 = compare.getLocation().getTop() + compare.getLocation().getHeight();

                        //右上角坐标
                        int y22 = y3;
                        int x22 = x4;

                        if (       ((x1 < (x3 + width) && x1 > (x3 - width))
                                && (y1 < (y3 + width) && y1 > (y3 - width)))

                                ||

                                ((x2 < (x4 + width) && x2 > (x4 - width))
                                        && (y2 < (y4 + width) && y2 > (y4 - width)))

                                ||

                                ((x11 < (x22 + width) && x11 > (x22 - width))
                                        && (y11 < (y22 + width) && y11 > (y22 - width)))

                                ) {

                            List<Dishes> compareDishes = compare.getDishes();
                            if (compareDishes != null && compareDishes.size() > 0) {
                                if (huaweiProduct.getScore() < 0.98) {
                                    if (compareDishes.get(0).getScore() > 0.7) {
                                        addedFlag = true;
                                        continue;
                                    }
                                }
                            }
                            logger.info("检测到云澎菜品库商品,id:" + huaweiProduct.getProductId() +
                                    ",name=" + huaweiProduct.getProductName() + ",baiduTop:" + compare.getLocation().getTop());


                            NeedReplacedProduct needReplacedProduct = new NeedReplacedProduct();
                            needReplacedProduct.setHuaweiProduct(huaweiProduct);
                            needReplacedProduct.setBaiduResult(compare);
                            needReplacedProduct.setHandled(false);
                            needReplacedList.add(needReplacedProduct);

                            addedFlag = true;
                        }
                    }
                }

                if (!addedFlag) {
                    NeedReplacedProduct needReplacedProduct = new NeedReplacedProduct();
                    needReplacedProduct.setHuaweiProduct(huaweiProduct);
                    needReplacedProduct.setBaiduResult(null);
                    needReplacedProduct.setHandled(false);
                    needReplacedList.add(needReplacedProduct);
                }
            }
        }else {
            needReplacedList = null;
        }

        try {
            List<ImgTag> imgTagList = new ArrayList<>();

            ThreadManager.executorService.submit(() -> {
                LogProductRec logProductRec = new LogProductRec();
                logProductRec.setFilepath(filename);
                logProductRec.setOutputFilepath(outputFilepath);
                logProductRec.setShopId(shopId);
                logProductRec.setCreateTime(date);
                logProductRec.setImgSrcNetUrl(sourceImgOnInternet);
                logProductRec.setRecResult(baiduRecResult);
                logProductRec.setImgResultNetUrl(imgUrl);
                logProductRecMapper.insert(logProductRec);
            });

            long endTime22 = System.currentTimeMillis();
            logger.info("搜索比对云澎菜品库时间=" + endTime22 + ", intelval=" + (endTime22 - endRec));

            ProductImgModel productImgModel = new ProductImgModel();
            productImgModel.setProductOrderNo(uuidFileName);
            productImgModel.setShopId(shopId);
            productImgModel.setSourceFilename(filename);
            productImgModel.setUuidFileName(uuidFileName);
            productImgModel.setImgUrl(imgUrl);
            productImgModel.setCurIpAddress(ipAddress);
            productImgModel.setSourceImgOnInternet(sourceImgOnInternet);
            productImgModel.setItemList(new ArrayList<>());

            ProductRecResultVONewWithLocation productRecResultVO = null;

            /*if (baiduRecResult.contains("error_code")) {
                throw new ServiceException("识别失败");
            }*/


            if (baiduSearchResult != null || huaRecResult != null) {
                final List<Result> searchResultList;
                if (baiduSearchResult != null) {
                    searchResultList = baiduSearchResult.getResult();
                }else {
                    searchResultList = null;
                }

                if ((searchResultList != null && searchResultList.size() > 0)
                        || huaRecResult != null
                        ) {
                    productRecResultVO = new ProductRecResultVONewWithLocation();
                    productRecResultVO.setProductList(new ArrayList<>());
                    productRecResultVO.setTotalFee(0l);
                    productRecResultVO.setRealFee(0l);

                    ThreadManager.executorService.submit(() -> {
                        if (searchResultList != null) {
                            addToProductImgCur(searchResultList, filename, shopId, uuidFileName, sourceImgOnInternet, needReplacedList, recType);
                        }
                    });

                    int seq = 1;

                    List<Result> needRemovedList = null;

                    if(searchResultList != null)
                    for (Result temp : searchResultList) {
                        int x1 = temp.getLocation().getLeft();
                        int y1 = temp.getLocation().getTop();

                        int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                        int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();


                        for (Result compare : searchResultList) {
                            int x3 = compare.getLocation().getLeft();
                            int y3 = compare.getLocation().getTop();

                            int x4 = compare.getLocation().getLeft() + compare.getLocation().getWidth();
                            int y4 = compare.getLocation().getTop() + compare.getLocation().getHeight();


                            if (x1 < x3 && y1 < y3
                                    && x2 > x4 && y2 > y4
                                    ) {
                                logger.info("检测有图片包含: top=" + temp.getLocation().getTop());
                                if (needRemovedList == null) {
                                    needRemovedList = new ArrayList<>();
                                }
                                needRemovedList.add(temp);
                            }
                        }

                        if(needReplacedList != null && needReplacedList.size() > 0)
                        for (NeedReplacedProduct needReplacedProduct : needReplacedList) {
                            HuaweiProduct huaweiProduct = needReplacedProduct.getHuaweiProduct();
                            int y3 = huaweiProduct.getLocation().get(0).intValue();
                            int x3 = huaweiProduct.getLocation().get(1).intValue();

                            int y4 = huaweiProduct.getLocation().get(2).intValue();
                            int x4 = huaweiProduct.getLocation().get(3).intValue();

                            if (x1 < x3 && y1 < y3
                                    && x2 > x4 && y2 > y4
                                    ) {
                                logger.info("本地识别检测有图片包含: top=" + temp.getLocation().getTop());
                                if (needRemovedList == null) {
                                    needRemovedList = new ArrayList<>();
                                }
                                needRemovedList.add(temp);
                            }
                        }
                    }

                    if(searchResultList != null){
                        boolean errorExist = false;
                        for (Result temp : searchResultList) {
                            List<Dishes> dishesList = temp.getDishes();
                            if (dishesList == null || dishesList.size() == 0) {
                                errorExist = true;
                                break;
                            }
                        }

                        if (errorExist) {
                            long errorExistStart = System.currentTimeMillis();
                            int index = 0;
                            List<Future<RecResult>> recFutureList = new ArrayList<>();

                            for (Result temp : searchResultList) {
                                NeedReplacedProduct needReplacedProduct = null;
                                if (needReplacedList != null) {
                                    for (NeedReplacedProduct tempNeedReplacedProduct : needReplacedList) {
                                        if (tempNeedReplacedProduct.getBaiduResult() != null) {
                                            if (tempNeedReplacedProduct.getBaiduResult().getLocation().getTop() == temp.getLocation().getTop()
                                                    && tempNeedReplacedProduct.getBaiduResult().getLocation().getWidth() == temp.getLocation().getWidth()
                                                    && tempNeedReplacedProduct.getBaiduResult().getLocation().getHeight() == temp.getLocation().getHeight()
                                                    && tempNeedReplacedProduct.getBaiduResult().getLocation().getLeft() == temp.getLocation().getLeft()
                                                    ) {
                                                needReplacedProduct = tempNeedReplacedProduct;
                                                tempNeedReplacedProduct.setHandled(true);

                                                break;
                                            }
                                        }
                                    }
                                }

                                ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                                        = new ProductRecResultDetailVONewWithLocation();

                                final Product[] product = new Product[1];

                                final Integer productId;

                                if (needReplacedProduct != null) {
                                    productId = needReplacedProduct.getHuaweiProduct().getProductId();
                                    double score = 0.9;
                                    productRecResultDetailVO.setConfident(1);

                                    int y1 = needReplacedProduct.getHuaweiProduct().getLocation().get(0).intValue();
                                    int x1 = needReplacedProduct.getHuaweiProduct().getLocation().get(1).intValue();

                                    int y2 = needReplacedProduct.getHuaweiProduct().getLocation().get(2).intValue();
                                    int x2 = needReplacedProduct.getHuaweiProduct().getLocation().get(3).intValue();


                                    if (x2 > x1) {
                                        temp.getLocation().setWidth(x2 - x1);
                                    }else {
                                        temp.getLocation().setWidth(x1 - x2);
                                    }
                                    if (y2 > y1) {
                                        temp.getLocation().setHeight(y2 - y1);
                                    }else {
                                        temp.getLocation().setHeight(y1 - y2);
                                    }

                                    productRecResultDetailVO.setConfident(1);
                                    product[0] = productMapper.selectByPrimaryKey(productId);

                                    String label = product[0].getName();

                                    ImgTag imgTag = new ImgTag();
                                    imgTag.setX1(x1);
                                    imgTag.setY1(y1);
                                    imgTag.setX2(x2);
                                    imgTag.setY2(y2);
                                    imgTag.setLabel(label);
                                    imgTag.setScore(1);
                                    imgTagList.add(imgTag);

                                    /**
                                     * save ProductImgDetailModel
                                     */
                                    ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                                    productImgDetailModel.setProductName(product[0].getName());
                                    productImgDetailModel.setProductId(product[0].getId());
                                    productImgDetailModel.setSeq(seq);
                                    productImgDetailModel.setLeft(x1);
                                    productImgDetailModel.setTop(y1);
                                    productImgDetailModel.setWidth(temp.getLocation().getWidth());
                                    productImgDetailModel.setHeight(temp.getLocation().getHeight());
                                    productImgDetailModel.setScore(score);
                                    productImgModel.getItemList().add(productImgDetailModel);
                                    ///----end

                                    productRecResultDetailVO.setX1(x1);
                                    productRecResultDetailVO.setX2(x2);
                                    productRecResultDetailVO.setY1(y1);
                                    productRecResultDetailVO.setY2(y2);

                                    productRecResultDetailVO.setProductName(product[0].getName());
                                    productRecResultDetailVO.setProductId(product[0].getId());
                                    productRecResultDetailVO.setProductPrice(product[0].getPrice());
                                    productRecResultDetailVO.setItemCount(1);
                                    productRecResultDetailVO.setSeq(seq);

                                    productRecResultVO.getProductList().add(productRecResultDetailVO);
                                    productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                                            + product[0].getPrice().longValue());

                                }else{
                                    //针对框出来不识别的情况
                                    logger.info("======框出来不识别:{}, {}, {}, {}", temp.getLocation().getTop(),
                                            temp.getLocation().getLeft(), temp.getLocation().getWidth(), temp.getLocation().getHeight());


                                    Integer tempSeq = seq;
                                    Integer tempIndex = index;

                                    ProductRecResultVONewWithLocation tempProductRecResultVO = productRecResultVO;
                                    Future<RecResult> localRecFuture = ThreadManager.executorService.submit((Callable) () ->
                                    {
                                        long reRecStart = System.currentTimeMillis();
                                        handleNotRecImg(filename, shopId, uuidFileName,
                                                temp, tempProductRecResultVO, tempSeq,
                                                productImgModel, imgTagList, branchId, tempIndex, tempToken, recType);
                                        long reRecEnd = System.currentTimeMillis();
                                        logger.info("======框出来重新识别时间:{}, tempIndex:{}", reRecEnd - reRecStart, tempIndex);
                                        return null;
                                    });

                                    recFutureList.add(localRecFuture);
                                }


                                index++;

                                seq++;
                            }

                            for (Future<RecResult> recResultFuture : recFutureList) {
                                recResultFuture.get();
                            }
                            long errorExistEnd = System.currentTimeMillis();

                            logger.info("======框不出来重新识别时间:{}", errorExistEnd - errorExistStart);
                        }else{
                            for (Result temp : searchResultList) {
                                List<Dishes> dishesList = temp.getDishes();
                                if (dishesList != null && dishesList.size() > 0) {
                                    double score = 0;
                                    String shopProductId = null;
                                    Set<String> shopProductIdList = new HashSet<>();
                                    for (Dishes dishes : dishesList) {
                                        if (!dishes.getBrief().contains("_")) {
                                            continue;
                                        }
                                        if (dishes.getScore() > score) {
                                            shopProductId = dishes.getBrief();
                                            score = dishes.getScore();
                                        }
                                        shopProductIdList.add(dishes.getBrief());
                                    }

                                    logger.info("score=" + score);

                                    if (score < 0.3) {
                                        continue;
                                    }

                                    int x1 = temp.getLocation().getLeft();
                                    int y1 = temp.getLocation().getTop();

                                    int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                                    int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();


                                    /**
                                     * 检测是否有图片包含
                                     */
                                    if (needRemovedList != null) {
                                        boolean flag = false;
                                        for (Result badResult : needRemovedList) {
                                            if (badResult.getLocation().getTop() == temp.getLocation().getTop()
                                                    && badResult.getLocation().getWidth() == temp.getLocation().getWidth()
                                                    && badResult.getLocation().getHeight() == temp.getLocation().getHeight()
                                                    && badResult.getLocation().getLeft() == temp.getLocation().getLeft()
                                                    ) {
                                                flag = true;
                                                break;
                                            }
                                        }

                                        if (flag) {
                                            logger.info("忽略检测有图片包含: top=" + temp.getLocation().getTop());
                                            continue;
                                        }
                                    }

                                    if (temp.getLocation().getWidth() > 900 && temp.getLocation().getHeight() > 600
                                            ) {
                                        logger.info("检测图片 宽高过大，width=" + temp.getLocation().getWidth());
                                        continue;
                                    }

                                    NeedReplacedProduct needReplacedProduct = null;
                                    if (needReplacedList != null) {

                                        for (NeedReplacedProduct tempNeedReplacedProduct : needReplacedList) {
                                            if (tempNeedReplacedProduct.getBaiduResult() != null) {
                                                if (tempNeedReplacedProduct.getBaiduResult().getLocation().getTop() == temp.getLocation().getTop()
                                                        && tempNeedReplacedProduct.getBaiduResult().getLocation().getWidth() == temp.getLocation().getWidth()
                                                        && tempNeedReplacedProduct.getBaiduResult().getLocation().getHeight() == temp.getLocation().getHeight()
                                                        && tempNeedReplacedProduct.getBaiduResult().getLocation().getLeft() == temp.getLocation().getLeft()
                                                        ) {
                                                    tempNeedReplacedProduct.setHandled(true);
                                                    needReplacedProduct = tempNeedReplacedProduct;

                                                    break;
                                                }
                                            }
                                        }
                                    }

                                    ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                                            = new ProductRecResultDetailVONewWithLocation();

                                    final Product[] product = new Product[1];

                                    final Integer productId;

                                    if (needReplacedProduct != null) {
                                        productId = needReplacedProduct.getHuaweiProduct().getProductId();
                                        score = 0.9;
                                        productRecResultDetailVO.setConfident(1);

                                        y1 = needReplacedProduct.getHuaweiProduct().getLocation().get(0).intValue();
                                        x1 = needReplacedProduct.getHuaweiProduct().getLocation().get(1).intValue();

                                        y2 = needReplacedProduct.getHuaweiProduct().getLocation().get(2).intValue();
                                        x2 = needReplacedProduct.getHuaweiProduct().getLocation().get(3).intValue();


                                        if (x2 > x1) {
                                            temp.getLocation().setWidth(x2 - x1);
                                        }else {
                                            temp.getLocation().setWidth(x1 - x2);
                                        }
                                        if (y2 > y1) {
                                            temp.getLocation().setHeight(y2 - y1);
                                        }else {
                                            temp.getLocation().setHeight(y1 - y2);
                                        }
                                    }else{
                                        if (shopProductId.contains("_")) {
                                            productId = Integer.valueOf(shopProductId.split("_")[1]);
                                        } else {
                                            productId = null;
                                        }
                                    }

                                    if (score < 0.75) {
                                        List<Integer> productIdList = new ArrayList<>();
                                        shopProductIdList.stream().forEach(sp -> {
                                            productIdList.add(Integer.valueOf(sp.split("_")[1]));
                                        });

                                        List<ProductRecOthersVO> productRecResultVOList = new ArrayList<>();

                                        if (DataLoadService.productMap != null) {
                                            for (Integer tempProductId : productIdList) {
                                                Product tempProduct = DataLoadService.productMap.get(tempProductId);
                                                if (tempProduct == null) {
                                                    tempProduct = productMapper.selectByPrimaryKey(tempProductId);
                                                }
                                                ProductRecOthersVO recResultVO = new ProductRecOthersVO();
                                                recResultVO.setProductName(tempProduct.getName());
                                                recResultVO.setProductPrice(tempProduct.getPrice());
                                                recResultVO.setProductId(tempProduct.getId());
                                                recResultVO.setItemCount(1);

                                                productRecResultVOList.add(recResultVO);

                                                if (tempProduct.getId().equals(productId)) {
                                                    product[0] = tempProduct;
                                                }
                                            }

                                            productRecResultVOList.sort(Comparator.comparing(ProductRecOthersVO::getProductPrice));
                                        }else{
                                            String productIdListStr = org.apache.commons.lang3.StringUtils.join(productIdList.toArray(), ",");
                                            List<Product> productList = productMapper.selectByIds(productIdListStr);



                                            productList.stream().forEach(p -> {
                                                ProductRecOthersVO recResultVO = new ProductRecOthersVO();
                                                recResultVO.setProductName(p.getName());
                                                recResultVO.setProductPrice(p.getPrice());
                                                recResultVO.setItemCount(1);
                                                recResultVO.setProductId(p.getId());

                                                productRecResultVOList.add(recResultVO);

                                                if (p.getId().equals(productId)) {
                                                    product[0] = p;
                                                }
                                            });
                                        }

                                        productRecResultDetailVO.setConfident(0);
                                        productRecResultDetailVO.setOtherProductList(productRecResultVOList);
                                    } else {
                                        productRecResultDetailVO.setConfident(1);
                                        product[0] = productMapper.selectByPrimaryKey(productId);
                                    }



                                    String label = product[0].getName();
//                            String label = product[0].getName() + "  " + PriceUtil.changeF2Y(product[0].getPrice()) + "元";

                                    ImgTag imgTag = new ImgTag();
                                    imgTag.setX1(x1);
                                    imgTag.setY1(y1);
                                    imgTag.setX2(x2);
                                    imgTag.setY2(y2);
                                    imgTag.setLabel(label);
                                    if (score < 0.75) {
                                        imgTag.setScore(0);
                                    } else {
                                        imgTag.setScore(1);
                                    }
                                    imgTagList.add(imgTag);

                                    /**
                                     * save ProductImgDetailModel
                                     */
                                    ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                                    productImgDetailModel.setProductName(product[0].getName());
                                    productImgDetailModel.setProductId(product[0].getId());
                                    productImgDetailModel.setSeq(seq);
                                    productImgDetailModel.setLeft(x1);
                                    productImgDetailModel.setTop(y1);
                                    productImgDetailModel.setWidth(temp.getLocation().getWidth());
                                    productImgDetailModel.setHeight(temp.getLocation().getHeight());
                                    productImgDetailModel.setScore(score);
                                    productImgModel.getItemList().add(productImgDetailModel);
                                    ///----end

                                    productRecResultDetailVO.setX1(x1);
                                    productRecResultDetailVO.setX2(x2);
                                    productRecResultDetailVO.setY1(y1);
                                    productRecResultDetailVO.setY2(y2);

                                    productRecResultDetailVO.setProductName(product[0].getName());
                                    productRecResultDetailVO.setProductId(product[0].getId());
                                    productRecResultDetailVO.setProductPrice(product[0].getPrice());
                                    productRecResultDetailVO.setItemCount(1);
                                    productRecResultDetailVO.setSeq(seq);

                                    productRecResultVO.getProductList().add(productRecResultDetailVO);
                                    productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                                            + product[0].getPrice().longValue());

                                    seq++;
                                }
                            }
                        }
                    }


                    if (needReplacedList != null) {
                        for (NeedReplacedProduct needReplacedProduct : needReplacedList) {
                            if (!needReplacedProduct.isHandled()) {
                                Product product = productMapper.selectByPrimaryKey(needReplacedProduct.getHuaweiProduct().getProductId());

                                String label = needReplacedProduct.getHuaweiProduct().getProductName();

                                int y1 = needReplacedProduct.getHuaweiProduct().getLocation().get(0).intValue();
                                int x1 = needReplacedProduct.getHuaweiProduct().getLocation().get(1).intValue();

                                int y2 = needReplacedProduct.getHuaweiProduct().getLocation().get(2).intValue();
                                int x2 = needReplacedProduct.getHuaweiProduct().getLocation().get(3).intValue();

                                ImgTag imgTag = new ImgTag();
                                imgTag.setX1(x1);
                                imgTag.setY1(y1);
                                imgTag.setX2(x2);
                                imgTag.setY2(y2);
                                imgTag.setLabel(label);
                                imgTag.setScore(1);
                                imgTagList.add(imgTag);



                                /**
                                 * save ProductImgDetailModel
                                 */
                                ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                                productImgDetailModel.setProductName(needReplacedProduct.getHuaweiProduct().getProductName());
                                productImgDetailModel.setProductId(needReplacedProduct.getHuaweiProduct().getProductId());
                                productImgDetailModel.setSeq(seq);
                                productImgDetailModel.setLeft(x1);
                                productImgDetailModel.setTop(y1);
                                if (x2 > x1) {
                                    productImgDetailModel.setWidth(x2 - x1);
                                }else {
                                    productImgDetailModel.setWidth(x1 - x2);
                                }

                                if (y2 > y1) {
                                    productImgDetailModel.setHeight(y2 - y1);
                                }else {
                                    productImgDetailModel.setHeight(y1 - y2);
                                }
                                productImgDetailModel.setScore(1);

                                productImgModel.getItemList().add(productImgDetailModel);
                                ///----end

                                ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                                        = new ProductRecResultDetailVONewWithLocation();

                                productRecResultDetailVO.setX1(x1);
                                productRecResultDetailVO.setX2(x2);
                                productRecResultDetailVO.setY1(y1);
                                productRecResultDetailVO.setY2(y2);
                                productRecResultDetailVO.setConfident(1);

                                productRecResultDetailVO.setProductName(needReplacedProduct.getHuaweiProduct().getProductName());
                                productRecResultDetailVO.setProductId(needReplacedProduct.getHuaweiProduct().getProductId());

                                productRecResultDetailVO.setProductPrice(product.getPrice());
                                productRecResultDetailVO.setItemCount(1);
                                productRecResultDetailVO.setSeq(seq);

                                productRecResultVO.getProductList().add(productRecResultDetailVO);
                                productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                                        + product.getPrice().longValue());

                                seq++;
                            }
                        }
                    }

                    ThreadManager.executorService.submit(() -> {
                        try {
                            setKey(productImgModel.getProductOrderNo(), productImgModel, 60 * 60 * 1000);
                            ProductImgJsonInfo productImgJsonInfo = new ProductImgJsonInfo();
                            productImgJsonInfo.setProductContent(JsonUtil.toJson(productImgModel));
                            productImgJsonInfo.setProductOrderNo(productImgModel.getProductOrderNo());

                            productImgJsonInfoMapper.insert(productImgJsonInfo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });

                    productRecResultVO.setRealFee(productRecResultVO.getTotalFee());
                    productRecResultVO.setProductCount(productRecResultVO.getProductList().size());

                }

                if (productRecResultVO == null) {
                    return null;
                }

                String imgJson = JsonUtil.toJson(imgTagList);

                logger.info("imgJson==" + imgJson);
                String temp = java.util.Base64.getEncoder().encodeToString(imgJson.getBytes());
                logger.info(temp);

                imgJson = URLEncoder.encode(temp);
                logger.info(imgJson);

                long endTime2 = System.currentTimeMillis();
                logger.info("endTime3=" + endTime2 + ", intelval=" + (endTime2 - startTime));

                String tempOutputFilepath = outputFilepath.replaceAll("/usr/local/nginx/html", "/data/html");
                String tempFilename = filename.replaceAll("/usr/local/nginx/html", "/data/html");

                String drwaImgParam = "outputFilepath=" + tempOutputFilepath + "&filename=" + tempFilename + "&image=" + imgJson;

//                String drwaImgParam = "outputFilepath=" + outputFilepath + "&filename=" + filename + "&image=" + imgJson;

                HttpEntity entity = new HttpEntity<>(drwaImgParam, DEFAULT_JSON_HEADER);

                ResponseEntity<String> drwaImgResult = restTemplate.postForEntity("http://"+recIp+":8082/hello2", entity, String.class);

                logger.info(drwaImgResult.getBody());


                long endTime3 = System.currentTimeMillis();
                logger.info("endTime4=" + endTime3 + ", intelval=" + (endTime3 - endTime2));

                if ("ok".equals(drwaImgResult.getBody())) {

                    ShopPackageDiscount shopPackageDiscount = checkProductPackage(shopId, productRecResultVO);

                    if (shopPackageDiscount != null) {
                        productRecResultVO.setRealFee(shopPackageDiscount.getPrice());
                        productRecResultVO.setMealSetId(shopPackageDiscount.getId());
                        productRecResultVO.setMealSetName(shopPackageDiscount.getName());
                    }

                    return productRecResultVO;
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



























































    /**
     * 检查是否有套餐价格
     * @param shopId
     * @param productRecResultVO
     * @return
     */
    public ShopPackageDiscount checkProductPackage(Integer shopId, ProductRecResultVONewWithLocation productRecResultVO){

        if (productRecResultVO == null) {
            return null;
        }

        if (DataLoadService.shopPackageDiscountMap == null) {
            return null;
        }

        List<ShopPackageDiscount> shopPackageDiscountList =
                DataLoadService.shopPackageDiscountMap.get(shopId);

        if (shopPackageDiscountList == null) {
            return null;
        }

        List<ProductRecResultDetailVONewWithLocation> productList = productRecResultVO.getProductList();

        if (productList != null && productList.size() > 0) {
            Map<Integer, Integer> productCategoryCountMap = new HashMap<>();
            for (ProductRecResultDetailVONewWithLocation p : productList) {
                Product tempProduct = DataLoadService.productMap.get(p.getProductId());
                if (tempProduct == null) {
                    tempProduct = productMapper.selectByPrimaryKey(p.getProductId());
                }

                Integer count = productCategoryCountMap.get(tempProduct.getMinorcategoryid());

                if (count == null) {
                    count = 0;
                }

                count++;

                productCategoryCountMap.put(tempProduct.getMinorcategoryid(), count);
            }

            if (shopPackageDiscountList != null && shopPackageDiscountList.size() > 0) {
                ShopPackageDiscount target = null;
                for (ShopPackageDiscount shopPackageDiscount : shopPackageDiscountList) {
                    String content = shopPackageDiscount.getPackagecontent();
                    try {
                        List<PackageContent> packageContentList =
                                com.alibaba.fastjson.JSONObject.parseArray(content, PackageContent.class);

                        int correctCount = 0;
                        for (PackageContent packageContent : packageContentList) {
                            Integer categoryId = packageContent.getId();
                            if (productCategoryCountMap.containsKey(categoryId)
                                    && productCategoryCountMap.get(categoryId).intValue() == packageContent.getCount()
                                    ) {
                                correctCount++;
                            }else {
                                break;
                            }
                        }

                        if (correctCount == packageContentList.size()
                                && correctCount == productCategoryCountMap.size()
                                ) {
                            target = shopPackageDiscount;
                            break;
                        }
                    } catch (Exception e) {
                        logger.error("parse error:{}", e);
                        continue;
                    }
                }

                return target;
            }
        }

        return null;
    }


    public ProductRecResultVONewWithLocation searchImgNewWithProductOrderNo(String productOrderNo, String outputFilepath)
            throws Exception {
        ProductImgModel productImgModel = getProductImgFromCache(productOrderNo);

        try {
            ProductRecResultVONewWithLocation productRecResultVO = null;

            if (productImgModel == null) {
                return null;
            }
            List<ProductImgDetailModel> searchResultList = productImgModel.getItemList();

            productRecResultVO = new ProductRecResultVONewWithLocation();
            productRecResultVO.setProductList(new ArrayList<>());
            productRecResultVO.setRealFee(0l);
            productRecResultVO.setTotalFee(0l);

            List<Integer> productIdList = new ArrayList<>();
            for (ProductImgDetailModel temp : searchResultList) {
                productIdList.add(temp.getProductId());
            }
            String productIdListStr = org.apache.commons.lang3.StringUtils.join(productIdList.toArray(), ",");
            List<Product> productList = productMapper.selectByIds(productIdListStr);

            Map<Integer, Product> productMap = new HashMap<>();
            for (Product product : productList) {
                productMap.put(product.getId(), product);
            }

            List<ImgTag> imgTagList = new ArrayList<>();

            for (ProductImgDetailModel temp : searchResultList) {

                ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                        = new ProductRecResultDetailVONewWithLocation();

                productRecResultDetailVO.setConfident(1);

                int seq = temp.getSeq();

                int x1 = temp.getLeft();
                int y1 = temp.getTop();

                int x2 = temp.getLeft() + temp.getWidth();
                int y2 = temp.getTop() + temp.getHeight();

                Product product = productMap.get(temp.getProductId());
                String label = temp.getProductName() + "  " + PriceUtil.changeF2Y(product.getPrice()) + "元";

                ImgTag imgTag = new ImgTag();
                imgTag.setX1(x1);
                imgTag.setY1(y1);
                imgTag.setX2(x2);
                imgTag.setY2(y2);
                imgTag.setLabel(seq + "、" + label);
                imgTag.setScore(1);

                imgTagList.add(imgTag);

                productRecResultDetailVO.setX1(x1);
                productRecResultDetailVO.setX2(x2);
                productRecResultDetailVO.setY1(y1);
                productRecResultDetailVO.setY2(y2);

                productRecResultDetailVO.setProductName(product.getName());
                productRecResultDetailVO.setProductId(product.getId());
                productRecResultDetailVO.setProductPrice(product.getPrice());
                productRecResultDetailVO.setItemCount(1);
                productRecResultDetailVO.setSeq(seq);

                productRecResultVO.getProductList().add(productRecResultDetailVO);
                productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                        + product.getPrice().longValue());

            }


            productRecResultVO.setRealFee(productRecResultVO.getTotalFee());
            productRecResultVO.setProductCount(productRecResultVO.getProductList().size());

            String imgJson = JsonUtil.toJson(imgTagList);

            String temp = java.util.Base64.getEncoder().encodeToString(imgJson.getBytes());
            logger.info(temp);

            imgJson = URLEncoder.encode(temp);
            logger.info(imgJson);


            String drwaImgParam = "outputFilepath=" + outputFilepath +
                    "&filename=" + productImgModel.getSourceFilename() + "&image=" + imgJson;

            HttpEntity entity = new HttpEntity<>(drwaImgParam, DEFAULT_JSON_HEADER);

            ResponseEntity<String> drwaImgResult = restTemplate.postForEntity("http://"+recIp+":8082/hello2", entity, String.class);

            logger.info(drwaImgResult.getBody());


            if ("ok".equals(drwaImgResult.getBody())) {
                return productRecResultVO;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String addImg(Integer shopId, String filename, String tag, Integer branchId) throws Exception {

        logger.info("============addImg=shopId:" + shopId + "========branchId=" + branchId);
        String token = getBaiduToken(shopId, branchId);
        logger.info("============addImg=shopId:" + shopId + "========token=" + token);

        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/add?access_token=" + token;

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        String filePath = filename;
        byte[] imgData = FileUtil.read(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");

        String param = "image=" + imgParam + "&sub_lib=" + getKey(baiduAppidKey + shopId + branchId) + "&brief=" + tag;

        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            logger.info(result.getBody());
            /**
             * {"log_id": 379096853819015407, "cont_sign": "2743144346,4232638351"}
             */

            Map<String, String> m = JsonUtil.parse(result.getBody(), Map.class);

            if (StringUtils.hasText((String) m.get("cont_sign"))) {
                return (String) m.get("cont_sign");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public String addImgCur(Integer shopId, String filename, String tag, Integer branchId) throws Exception {

        Map<String, String> tokenMap = getBaiduTokenCur(shopId, branchId);
        String token = tokenMap.get("token");
        String appId = tokenMap.get("appId");

        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/add?access_token=" + token;

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
        DEFAULT_JSON_HEADER.setContentType(jsontype);


        String filePath = filename;
        byte[] imgData = FileUtil.read(filePath);
        String imgStr = Base64Util.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");

        String param = "image=" + imgParam + "&sub_lib=" + appId + "&brief=" + tag;

        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            logger.info(result.getBody());
            /**
             * {"log_id": 379096853819015407, "cont_sign": "2743144346,4232638351"}
             */

            Map<String, String> m = JsonUtil.parse(result.getBody(), Map.class);

            if (StringUtils.hasText((String) m.get("cont_sign"))) {
                return (String) m.get("cont_sign");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public List<Map<String, String>> addImgCurList(Integer shopId, String filename, String tag, Integer branchId) throws Exception {

        List<Map<String, String>> tokenList = getBaiduTokenCurList(shopId, branchId);

        if (tokenList != null) {
            List<Map<String, String>> resultList = new ArrayList<>();
            for (Map<String, String> map : tokenList) {
                String token = map.get("token");
                String appid = map.get("appid");
                String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/add?access_token=" + token;

                HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
                MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
                DEFAULT_JSON_HEADER.setContentType(jsontype);


                String filePath = filename;
                byte[] imgData = FileUtil.read(filePath);
                String imgStr = Base64Util.encode(imgData);
                String imgParam = URLEncoder.encode(imgStr, "UTF-8");

                String param = "image=" + imgParam + "&sub_lib=" + appid + "&brief=" + tag;

                try {
                    HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

                    ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

                    System.out.println(result.getBody());
                    /**
                     * {"log_id": 379096853819015407, "cont_sign": "2743144346,4232638351"}
                     */

                    Map<String, String> m = JsonUtil.parse(result.getBody(), Map.class);

                    if (StringUtils.hasText(m.get("cont_sign"))) {

                        String contSign = m.get("cont_sign");

                        Map<String, String> resultMap = new HashMap<>();
                        resultMap.put("appid", appid);
                        resultMap.put("contSign", contSign);

                        resultList.add(resultMap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return resultList;
        }


        return null;
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     *
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            Map<String, Object> m = JsonUtil.parse(result, Map.class);


            String access_token = (String) m.get("access_token");
            tokenExpireTime = new Long((Integer) m.get("expires_in"));
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    private List<Integer> existedShopIdList = new ArrayList<>();

    public Integer handleNotRecImg(String filename, Integer shopId
        , String uuidFileName, Result temp, ProductRecResultVONewWithLocation productRecResultVO, Integer seq
                                 ,ProductImgModel productImgModel, List<ImgTag> imgTagList, Integer branchId
                                    , Integer index, String token, Integer recType
    ){
        String localFilepath = "/usr/local/nginx/html/img/" + shopId;

        if (!existedShopIdList.contains(shopId)) {
            File file = new File(localFilepath);
            if (!file.exists()) {
                file.mkdir();
            }
            existedShopIdList.add(shopId);
            localFilepath +=  "/0000";
            file = new File(localFilepath);
            if (!file.exists()) {
                file.mkdir();
            }

            localFilepath += "/temp";
            File imgCutFile = new File(localFilepath);
            if (!imgCutFile.exists()) {
                imgCutFile.mkdir();
            }
        }else {
            localFilepath +=  "/0000";
            localFilepath += "/temp";
        }


        String cutImgPath = localFilepath + "/" + uuidFileName + "_cut" + index + ".png";
        String cutImgUrl = cutImgPath.replace("/usr/local/nginx/html", "http://" + ipAddress + ":8019");
        try {
            ImageUtil.cutImage(filename, cutImgPath
                    , temp.getLocation().getLeft(),
                    temp.getLocation().getTop(), temp.getLocation().getWidth(), temp.getLocation().getHeight());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        logger.info("===============cutImgPath==" + cutImgPath);


        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token=" + token;



        String imgParam = null;
        String fileBase64Content = null;
        try {
            fileBase64Content = ImageBase64Util.getImageBinary(cutImgPath);
            imgParam = URLEncoder.encode(fileBase64Content, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("fileBase64Content=={}, error={}", fileBase64Content, e);

            fileBase64Content = ImageBase64Util.getNetImageBinary(cutImgUrl);
            try {
                imgParam = URLEncoder.encode(fileBase64Content, "UTF-8");
            } catch (Exception e1) {
                e1.printStackTrace();
                return null;
            }
        }

        String param = "image=" + imgParam + "&top_num=" + 5;
        logger.info("info====");

//        logger.info("param===" + param);

        try {

            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = restTemplate.postForEntity(url, entity, String.class);


            logger.info("=====rec result====" + result.getBody());

            BaiduSearchResult baiduSearchResult = null;
            if (result.getBody().contains("282000") && result.getBody().contains("error")) {
                //try again
                result = restTemplate.postForEntity(url, entity, String.class);
                logger.info("=====rec result====try again======" + result.getBody());
                if (result.getBody().contains("282000") && result.getBody().contains("error")) {
                    if (recType == 1) {
                        logger.info("识别错误时非纠正界面不显示={}", cutImgUrl);
                        return null;
                    }
                    baiduSearchResult = new BaiduSearchResult();
                    Result tempResult = new Result();
                    tempResult.setDishes(new ArrayList<>());
                    //识别出错时，标记为未识别菜品
                    Dishes dishes = new Dishes();
                    dishes.setBrief(shopId + "_" + "1");//1为未识别菜品
                    dishes.setOriginScore(0.1);
                    dishes.setScore(0.1);
                    tempResult.getDishes().add(dishes);
                    baiduSearchResult.setResult(new ArrayList<>());
                    baiduSearchResult.getResult().add(tempResult);

                }else{
                    baiduSearchResult = JsonUtil.parse(result.getBody(), BaiduSearchResult.class);
                }

            }else{
                baiduSearchResult = JsonUtil.parse(result.getBody(), BaiduSearchResult.class);
            }

            if (baiduSearchResult != null) {
                List<Result> searchResultList = baiduSearchResult.getResult();

                if (searchResultList != null && searchResultList.size() > 0) {
                    Result recResult = searchResultList.get(0);
                    List<Dishes> dishesList = recResult.getDishes();
                    if (dishesList == null || dishesList.size() == 0) {
                        dishesList = new ArrayList<>();
                        if ((DataLoadService.shopRecOpenMap != null && DataLoadService.shopRecOpenMap.get(shopId) != null &&
                                DataLoadService.shopRecOpenMap.get(shopId).equals(1))) {
                            //纠正时候如有未识别的菜品，标记为未识别菜品
                            Dishes dishes = new Dishes();
                            dishes.setBrief(shopId + "_" + "1");//1为未识别菜品
                            dishes.setOriginScore(0.1);
                            dishes.setScore(0.1);
                            dishesList.add(dishes);
                        }else
                        if (recType == 1) {
                            //纠正时候如有未识别的菜品，标记为未识别菜品
                            Dishes dishes = new Dishes();
                            dishes.setBrief(shopId + "_" + "1");//1为未识别菜品
                            dishes.setOriginScore(0.1);
                            dishes.setScore(0.1);
                            dishesList.add(dishes);
                        }
                    }
                    if (dishesList != null && dishesList.size() > 0) {
                        double score = 0;
                        String shopProductId = null;
                        Set<String> shopProductIdList = new HashSet<>();
                        for (Dishes dishes : dishesList) {
                            if (!dishes.getBrief().contains("_")) {
                                continue;
                            }
                            if (dishes.getScore() > score) {
                                shopProductId = dishes.getBrief();
                                score = dishes.getScore();
                            }
                            shopProductIdList.add(dishes.getBrief());
                        }

                        logger.info("score=" + score);


                        int x1 = temp.getLocation().getLeft();
                        int y1 = temp.getLocation().getTop();

                        int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                        int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();

                        ProductRecResultDetailVONewWithLocation productRecResultDetailVO
                                = new ProductRecResultDetailVONewWithLocation();

                        final Product[] product = new Product[1];

                        final Integer finalProductId;
                        if (shopProductId.contains("_")) {
                            finalProductId = Integer.valueOf(shopProductId.split("_")[1]);
                        } else {
                            finalProductId = null;
                        }

                        if (score < 0.5) {
                            if (recType == 1) {
                                product[0] = noneRecProduct;
                                score = 0.2;
                                productRecResultDetailVO.setConfident(0);
                            }else {
                                logger.info("未识别菜品在不纠正界面不显示={}", cutImgUrl, score);
                                return null;
                            }
                        }else if (score < 0.75) {
                            List<Integer> productIdList = new ArrayList<>();
                            shopProductIdList.stream().forEach(sp -> {
                                productIdList.add(Integer.valueOf(sp.split("_")[1]));
                            });

                            List<ProductRecOthersVO> productRecResultVOList = new ArrayList<>();

                            if (DataLoadService.productMap != null) {
                                for (Integer tempProductId : productIdList) {
                                    Product tempProduct = null;
                                    if (tempProductId == 1 || tempProductId < 0) {
                                        tempProduct = noneRecProduct;
                                    }else{
                                        tempProduct = DataLoadService.productMap.get(tempProductId);
                                        if (tempProduct == null) {
                                            tempProduct = productMapper.selectByPrimaryKey(tempProductId);
                                        }
                                    }
                                    ProductRecOthersVO recResultVO = new ProductRecOthersVO();
                                    recResultVO.setProductName(tempProduct.getName());
                                    recResultVO.setProductId(tempProduct.getId());
                                    recResultVO.setProductPrice(tempProduct.getPrice());
                                    recResultVO.setItemCount(1);

                                    productRecResultVOList.add(recResultVO);

                                    if (tempProduct.getId().equals(finalProductId)) {
                                        product[0] = tempProduct;
                                    }
                                }

                                productRecResultVOList.sort(Comparator.comparing(ProductRecOthersVO::getProductPrice));
                            }else{
                                String productIdListStr = org.apache.commons.lang3.StringUtils.join(productIdList.toArray(), ",");
                                List<Product> productList = productMapper.selectByIds(productIdListStr);



                                productList.stream().forEach(p -> {
                                    ProductRecOthersVO recResultVO = new ProductRecOthersVO();
                                    recResultVO.setProductName(p.getName());
                                    recResultVO.setProductPrice(p.getPrice());
                                    recResultVO.setProductId(p.getId());
                                    recResultVO.setItemCount(1);

                                    productRecResultVOList.add(recResultVO);

                                    if (p.getId().equals(finalProductId)) {
                                        product[0] = p;
                                    }
                                });
                            }

                            productRecResultDetailVO.setConfident(0);
                            productRecResultDetailVO.setOtherProductList(productRecResultVOList);
                        } else {
                            productRecResultDetailVO.setConfident(1);
                            if (finalProductId < -1000) {
                                product[0] = productMapper.selectByPrimaryKey(Math.abs(finalProductId));
                            }else {
                                product[0] = productMapper.selectByPrimaryKey(finalProductId);
                            }

                            if (product[0] == null || product[0].getDeleted()) {
                                product[0] = noneRecProduct;
                                score = 0.2;
                                productRecResultDetailVO.setConfident(0);
                            }
                        }



                        String label = product[0].getName();
//                            String label = product[0].getName() + "  " + PriceUtil.changeF2Y(product[0].getPrice()) + "元";

                        ImgTag imgTag = new ImgTag();
                        imgTag.setX1(x1);
                        imgTag.setY1(y1);
                        imgTag.setX2(x2);
                        imgTag.setY2(y2);
                        imgTag.setLabel(label);
//                        imgTag.setLabel(label);
                        if (score < 0.75) {
                            imgTag.setScore(0);
                        } else {
                            imgTag.setScore(1);
                        }
                        imgTagList.add(imgTag);

                        /**
                         * save ProductImgDetailModel
                         */
                        ProductImgDetailModel productImgDetailModel = new ProductImgDetailModel();
                        productImgDetailModel.setProductName(product[0].getName());
                        productImgDetailModel.setProductId(product[0].getId());
                        productImgDetailModel.setSeq(seq);
                        productImgDetailModel.setLeft(x1);
                        productImgDetailModel.setTop(y1);
                        productImgDetailModel.setWidth(temp.getLocation().getWidth());
                        productImgDetailModel.setHeight(temp.getLocation().getHeight());
                        productImgDetailModel.setScore(score);
                        productImgModel.getItemList().add(productImgDetailModel);
                        ///----end

                        productRecResultDetailVO.setX1(x1);
                        productRecResultDetailVO.setX2(x2);
                        productRecResultDetailVO.setY1(y1);
                        productRecResultDetailVO.setY2(y2);

                        productRecResultDetailVO.setProductName(product[0].getName());
                        productRecResultDetailVO.setProductId(product[0].getId());
                        productRecResultDetailVO.setProductPrice(product[0].getPrice());
                        productRecResultDetailVO.setItemCount(1);
                        productRecResultDetailVO.setSeq(seq);

                        productRecResultVO.getProductList().add(productRecResultDetailVO);
                        productRecResultVO.setTotalFee(productRecResultVO.getTotalFee().longValue()
                                + product[0].getPrice().longValue());

                        seq++;

                        return seq;
                    }
                }
            }
        } catch (Exception e) {

            logger.info("===============end =====rec error:" + e.getMessage());
        }

        return null;
    }

    private void addToProductImgWithHuawei(List<Result> searchResultList, String filename,
                                 Integer shopId, String uuidFileName, String sourceImgOnInternet, List<NeedReplacedProduct> needReplacedList) {
        logger.info("===============start =====addToProductImg");
        try {

            List<Integer> huaweiProductIdList = null;
            if (needReplacedList != null) {
                huaweiProductIdList = new ArrayList<>();
                for (NeedReplacedProduct needReplacedProduct : needReplacedList) {
                    huaweiProductIdList.add(needReplacedProduct.getHuaweiProduct().getProductId());
                }
            }
            int i = 0;
            for (Result temp : searchResultList) {
                List<Dishes> dishesList = temp.getDishes();
                if (dishesList != null && dishesList.size() > 0) {
                    double score = 0;
                    String shopProductId = null;
                    for (Dishes dishes : dishesList) {
                        if (dishes.getScore() > score) {
                            score = dishes.getScore();
                            shopProductId = dishes.getBrief();
                        }
                    }

                    if (dishesList.size() == 1 && score > 0.6) {
                        logger.info("一个菜品且分数大于0.6");
                    } else {
                        if (score < 0.85) {
                            continue;
                        }
                    }



                    Integer productId = null;
                    Integer branchId = null;
                    if (shopProductId.contains("_")) {
                        productId = Integer.valueOf(shopProductId.split("_")[1]);
                        Product p = productMapper.selectByPrimaryKey(productId);
                        if (p != null) {
                            branchId = p.getStoreid();
                        }else {
                            logger.error("error addToProductImg, pid = " + productId);
                        }
                    }

                    /**
                     * 华为识别后的商品不参与补图
                     */
                    if (huaweiProductIdList != null && huaweiProductIdList.contains(productId)) {
                        logger.error("local rec 识别后的商品不参与补图, pid = " + productId);
                        continue;
                    }

                    String localFilepath = "/usr/local/nginx/html/img/" + shopId;

                    File file = new File(localFilepath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    localFilepath +=  "/" + productId;
                    file = new File(localFilepath);
                    if (!file.exists()) {
                        file.mkdir();
                    }

                    localFilepath += "/temp";
                    File imgCutFile = new File(localFilepath);
                    if (!imgCutFile.exists()) {
                        imgCutFile.mkdir();
                    }

                    StringBuffer cutImgUrl = new StringBuffer("http://")
                            .append(ipAddress)
                            .append(":8019/img/")
                            .append(shopId)
                            .append("/")
                            .append(productId)
                            .append("/temp/")
                            .append(uuidFileName)
                            .append("_cut")
                            .append(i)
                            .append(".png");

                    String cutImgPath = localFilepath + "/" + uuidFileName + "_cut" + i + ".png";
                    ImageUtil.cutImage(filename, cutImgPath
                            , temp.getLocation().getLeft(),
                            temp.getLocation().getTop(), temp.getLocation().getWidth(), temp.getLocation().getHeight());

                    logger.info("===============cutImgPath==" + cutImgPath);


                    if (!reRecognize(shopId, cutImgPath, productId, branchId)) {
                        logger.info("===============reRecognize===false");
                        continue;
                    }
                    logger.info("===============reRecognize===true");

                    List<LogProductImgFromUser> productImgList = productService.getProductImgFromUserList(productId);

                    String contSign = null;
                    if (productImgList != null && productImgList.size() > 20) {

                        logger.info("====" + productId + "===========底库图片大于20张===删除最老的一张=");

                        LogProductImgFromUser tempLogProductImgFromUser = productImgList.get(0);


                        boolean delResult = delImg(tempLogProductImgFromUser.getContSign(), shopId, branchId);

                        //删除最老的一张
                        if(!delResult){
                            LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                            logShopBaiduImgDel.setLogId(tempLogProductImgFromUser.getId());
                            logShopBaiduImgDel.setStatus(0);
                            logShopBaiduImgDel.setImgType(2);

                            logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                        }

                    }

                    logger.info("====" + productId + "===========添加底库图片");
                    contSign = addImg(shopId, cutImgPath, shopId + "_" + productId, branchId);

                    LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
                    logProductImgFromUser.setContSign(contSign);
                    logProductImgFromUser.setCreateTime(new Date());
                    logProductImgFromUser.setCutImg(cutImgPath);
                    logProductImgFromUser.setSourceImg(filename);
                    logProductImgFromUser.setProductId(productId);
                    logProductImgFromUser.setShopId(shopId);
                    logProductImgFromUser.setFromCorrect(0);
                    logProductImgFromUser.setImgSrcNetUrl(sourceImgOnInternet);
                    logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                    logProductImgFromUser.setBranchId(branchId);
                    logProductImgFromUser.setSubDb(0);

                    if (contSign != null) {
                        logProductImgFromUser.setBaiduDeleted(0);
                    } else {
                        logProductImgFromUser.setBaiduDeleted(1);
                    }

                    logProductImgFromUserMapper.insert(logProductImgFromUser);

                    int x1 = temp.getLocation().getLeft();
                    int y1 = temp.getLocation().getTop();

                    int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                    int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();

                    logger.info("===============end =====addToProductImg");

                    i++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void addToProductImgCur(List<Result> searchResultList, String filename,
                                 Integer shopId, String uuidFileName, String sourceImgOnInternet,
                                 List<NeedReplacedProduct> needReplacedList, Integer type) {
        logger.info("===============start =====addToProductImg");
        try {

            List<Integer> huaweiProductIdList = null;
            if (needReplacedList != null) {
                huaweiProductIdList = new ArrayList<>();
                for (NeedReplacedProduct needReplacedProduct : needReplacedList) {
                    huaweiProductIdList.add(needReplacedProduct.getHuaweiProduct().getProductId());
                }
            }
            int i = 0;
            for (Result temp : searchResultList) {
                List<Dishes> dishesList = temp.getDishes();
                if (dishesList != null && dishesList.size() > 0) {
                    double score = 0;
                    String shopProductId = null;
                    for (Dishes dishes : dishesList) {
                        if (dishes.getScore() > score) {
                            score = dishes.getScore();
                            shopProductId = dishes.getBrief();
                        }
                    }

                    if (dishesList.size() == 1 && score > 0.6) {
                        logger.info("一个菜品且分数大于0.6");
                    } else {
                        if (score < 0.85) {
                            continue;
                        }
                    }



                    Integer productId = null;
                    Integer branchId = null;
                    if (shopProductId.contains("_")) {
                        productId = Integer.valueOf(shopProductId.split("_")[1]);
                        Product p = productMapper.selectByPrimaryKey(productId);
                        if (p != null) {
                            branchId = p.getStoreid();
                        }else {
                            logger.error("error addToProductImg, pid = " + productId);
                        }
                    }

                    /**
                     * 华为识别后的商品不参与补图
                     */
                    if (huaweiProductIdList != null && huaweiProductIdList.contains(productId)) {
                        logger.error("local rec 识别后的商品不参与补图, pid = " + productId);
                        continue;
                    }

                    String localFilepath = "/usr/local/nginx/html/img/" + shopId;

                    File file = new File(localFilepath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    localFilepath +=  "/" + productId;
                    file = new File(localFilepath);
                    if (!file.exists()) {
                        file.mkdir();
                    }

                    localFilepath += "/temp";
                    File imgCutFile = new File(localFilepath);
                    if (!imgCutFile.exists()) {
                        imgCutFile.mkdir();
                    }

                    StringBuffer cutImgUrl = new StringBuffer("http://")
                            .append(ipAddress)
                            .append(":8019/img/")
                            .append(shopId)
                            .append("/")
                            .append(productId)
                            .append("/temp/")
                            .append(uuidFileName)
                            .append("_cut")
                            .append(i)
                            .append(".png");

                    String cutImgPath = localFilepath + "/" + uuidFileName + "_cut" + i + ".png";
                    ImageUtil.cutImage(filename, cutImgPath
                            , temp.getLocation().getLeft(),
                            temp.getLocation().getTop(), temp.getLocation().getWidth(), temp.getLocation().getHeight());

                    logger.info("===============cutImgPath==" + cutImgPath);


                    if (!reRecognize(shopId, cutImgPath, productId, branchId)) {
                        logger.info("===============reRecognize===false");
                        continue;
                    }
                    logger.info("===============reRecognize===true");

                    List<LogProductImgFromUser> productImgList = productService.getProductImgFromUserList(productId);

                    String contSign = null;
                    List<Map<String, String>> contSignCurList = null;
                    if (productImgList != null && productImgList.size() > 20) {

                        logger.info("====" + productId + "===========底库图片大于20张====");
                    }else {
                        logger.info("====" + productId + "===========添加底库图片");
                        contSign = addImg(shopId, cutImgPath, shopId + "_" + productId, branchId);

                        if (DataLoadService.shopBaiduUrlCurListMap != null
                                && DataLoadService.shopBaiduUrlCurListMap.get(shopId) != null) {
                            contSignCurList = addImgCurList(shopId, cutImgPath, shopId + "_" + productId, branchId);
//                            contSignCur = addImgCur(shopId, cutImgPath, shopId + "_" + productId, branchId);
                        }
                    }

                    LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
                    logProductImgFromUser.setContSign(contSign);
                    logProductImgFromUser.setCreateTime(new Date());
                    logProductImgFromUser.setCutImg(cutImgPath);
                    logProductImgFromUser.setSourceImg(filename);
                    logProductImgFromUser.setProductId(productId);
                    logProductImgFromUser.setShopId(shopId);
                    logProductImgFromUser.setFromCorrect(0);
                    logProductImgFromUser.setImgSrcNetUrl(sourceImgOnInternet);
                    logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                    logProductImgFromUser.setBranchId(branchId);
                    logProductImgFromUser.setSubDb(0);

                    if (contSign != null) {
                        logProductImgFromUser.setBaiduDeleted(0);
                    } else {
                        logProductImgFromUser.setBaiduDeleted(1);
                    }

                    if (contSignCurList != null && contSignCurList.size() > 0) {
                        for (Map<String, String> map : contSignCurList) {
                            String appid = map.get("appid");
                            String contSignCur = map.get("contSign");
                            LogProductImgFromUser logProductImgCur = new LogProductImgFromUser();
                            BeanUtils.copyProperties(logProductImgFromUser, logProductImgCur);
                            logProductImgCur.setContSign(contSignCur);
                            logProductImgCur.setSubDb(1);
                            logProductImgCur.setBaiduAppId(appid);
                            logProductImgFromUserMapper.insertSelective(logProductImgCur);
                        }
                    }
                    logProductImgFromUserMapper.insert(logProductImgFromUser);

                    int x1 = temp.getLocation().getLeft();
                    int y1 = temp.getLocation().getTop();

                    int x2 = temp.getLocation().getLeft() + temp.getLocation().getWidth();
                    int y2 = temp.getLocation().getTop() + temp.getLocation().getHeight();

                    logger.info("===============end =====addToProductImg");

                    i++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void addToProductImg(List<Result> searchResultList, String filename,
                                 Integer shopId, String uuidFileName, String sourceImgOnInternet) {
        addToProductImgWithHuawei(searchResultList, filename, shopId, uuidFileName, sourceImgOnInternet, null);

    }


    public void correctProductImg(ProductCorrectForm productCorrectForm) {

        if (productCorrectForm.getItemList() == null || productCorrectForm.getItemList().size() == 0) {
            return;
        }

        logger.info("===============start =====correctProductImg");
        try {
            ProductImgModel productImgModel = getProductImgFromCache(productCorrectForm.getProductOrderNo());

            if (productImgModel == null) {
                return;
            }


            if (productImgModel.getItemList() != null && productImgModel.getItemList().size() > 0) {
                int i = 0;

                Map<Integer, ProductImgDetailModel> productImgDetailModelMap = new HashMap<>();

                Map<Integer, ProductCorrectItemForm> productCorrectItemFormHashMap = new HashMap<>();


                for (ProductCorrectItemForm productCorrectItemForm : productCorrectForm.getItemList()) {
                    productCorrectItemFormHashMap.put(productCorrectItemForm.getSeq(), productCorrectItemForm);
                }

                Map<Integer, Integer> productIdMap = new HashMap<>();
                for (ProductImgDetailModel productImgDetailModel : productImgModel.getItemList()) {
                    ProductCorrectItemForm productCorrectItemForm = productCorrectItemFormHashMap.get(productImgDetailModel.getSeq());

                    if (productCorrectItemForm != null) {
                        productIdMap.put(productCorrectItemForm.getProductId(), productImgDetailModel.getProductId());

                        productImgDetailModel.setProductId(productCorrectItemForm.getProductId());
                        productImgDetailModel.setProductName(productCorrectItemForm.getProductName());

                        productImgDetailModelMap.put(productImgDetailModel.getSeq(), productImgDetailModel);
                    }
                }

                String productImgModeStr = JsonUtil.toJson(productImgModel);
                logger.info(productImgModeStr);

                /**
                 * save to cache and db
                 */
                setKey(productCorrectForm.getProductOrderNo(), productImgModel, 60 * 60 * 1000);
                ProductImgJsonInfo productImgJsonInfo = new ProductImgJsonInfo();
                productImgJsonInfo.setProductContent(productImgModeStr);

                Condition condition = new Condition(ProductImgJsonInfo.class);
                condition.or().andEqualTo("productOrderNo", productCorrectForm.getProductOrderNo());
                productImgJsonInfoMapper.updateByConditionSelective(productImgJsonInfo, condition);
                //---end save---

                List<Integer> productIdList = null;
                if(DataLoadService.shopYpProductListMap != null){
                    List<ProductYpRef> temp = DataLoadService.shopYpProductListMap.get(productImgModel.getShopId());

                    if (temp != null && temp.size() > 0) {
                        productIdList = temp.stream().map(ProductYpRef::getProductId).collect(Collectors.toList());
                    }
                }




                Integer targetShopId;
                Integer targetBranchId = null;
                if (DataLoadService.shopProductRefMap != null) {
                    targetShopId = DataLoadService.shopProductRefMap.get(productImgModel.getShopId());
                    Condition branchCondtion = new Condition(Branch.class);
                    branchCondtion.or().andEqualTo("shopId", targetShopId);
                    List<Branch> branchList = branchMapper.selectByCondition(branchCondtion);
                    if (branchList != null && branchList.size() > 0) {
                        targetBranchId = branchList.get(0).getBranchId();
                    }
                }else{
                    targetShopId = null;
                }


                for (ProductCorrectItemForm productCorrectItemForm : productCorrectForm.getItemList()) {
                    if (productIdList != null && productIdList.contains(productCorrectItemForm.getProductId())) {
                        logger.info("忽略云澎菜品库商品:" + productCorrectItemForm.getProductName());
                        continue;
                    }


                    ProductImgDetailModel productImgDetailModel = productImgDetailModelMap.get(productCorrectItemForm.getSeq());

                    Integer productId = productCorrectItemForm.getProductId();

                    Integer targetProductId;
                    if (targetShopId != null) {
                        Product sourceProduct = productMapper.selectByPrimaryKey(productId);
                        Condition productConditon = new Condition(Product.class);
                        productConditon.or().andEqualTo("shopid", targetShopId)
                                .andEqualTo("searchcode", sourceProduct.getSearchcode())
                        ;
                        List<Product> productList = productMapper.selectByCondition(productConditon);
                        if (productList != null && productList.size() > 0) {

                            Product targetProduct = productList.get(0);
                            targetProductId = targetProduct.getId();
                        }else{
                            targetProductId = null;
                        }
                    }else {
                        targetProductId = null;
                    }

                    if (productId != 1) {
                        /**
                         * 删除旧图片
                         */

                        logger.info("删除旧图片productId=" + productId);

                        ThreadManager.executorService.submit(() -> {
                            if (targetProductId != null) {
                                deleteProductImgCur(targetProductId);
                            }
                            deleteProductImgCur(productId);
                        });
                    }


                    if (productImgDetailModel.getScore() > 0.75) {
                        Integer oldProductId = productIdMap.get(productId);
                        if (oldProductId != 1) {
                            logger.info("被修改的菜品分数大于0.75,删除旧图片oldProductId=" + oldProductId);
                            ThreadManager.executorService.submit(() -> {
                                if (targetProductId != null) {
                                    deleteProductImgCur(targetProductId);
                                }
                                deleteProductImgCur(oldProductId);
                            });
                        }
                    }


                    String localFilepath = "/usr/local/nginx/html/img/" + productImgModel.getShopId();

                    File shopFile = new File(localFilepath);
                    if (!shopFile.exists()) {
                        shopFile.mkdir();
                    }

                    localFilepath = localFilepath + "/" + productId;

                    File imgCutFile = new File(localFilepath);
                    if (!imgCutFile.exists()) {
                        imgCutFile.mkdir();
                    }
                    localFilepath += "/temp";

                    File imgCutFileTemp = new File(localFilepath);
                    if (!imgCutFileTemp.exists()) {
                        imgCutFileTemp.mkdir();
                    }

                    StringBuffer cutImgUrl = new StringBuffer("http://")
                            .append(ipAddress)
                            .append(":8019/img/")
                            .append(productImgModel.getShopId())
                            .append("/")
                            .append(productId)
                            .append("/temp/")
                            .append(productImgModel.getUuidFileName())
                            .append("_cut")
                            .append(i)
                            .append(".png");

                    String cutImgPath = localFilepath + "/" + productImgModel.getUuidFileName() + "_cut" + i + ".png";
                    i++;

                    String sourceFilePath = productImgModel.getSourceFilename();
                    String sourceFilePathOnNet = productImgModel.getSourceImgOnInternet();
                    if (productImgModel.getCurIpAddress() != null &&
                            productImgModel.getCurIpAddress().equals(ipAddress)
                            ) {
                        LoggerUtil.console.info("source file ip : {}, sourceFilePath:", productImgModel.getCurIpAddress(), sourceFilePath);
                    } else {
                        LoggerUtil.console.info("source file ip : {}", productImgModel.getCurIpAddress());

                        String downloadNetFilepath = "/usr/local/nginx/html/img/" + productImgModel.getShopId() + "/" + productId + "/net";

                        File downloadNetFilepathFile = new File(downloadNetFilepath);
                        if (!downloadNetFilepathFile.exists()) {
                            downloadNetFilepathFile.mkdir();
                        }

                        int tempInt = new Random(100).nextInt();
                        downloadNetFilepath += "/" + productImgModel.getUuidFileName() + "." + tempInt + ".png";
                        ImageBase64Util.downloadNetImage(productImgModel.getSourceImgOnInternet(), downloadNetFilepath);

                        LoggerUtil.console.info("source file ip : {}, sourceFilePath:{}",
                                productImgModel.getCurIpAddress(), downloadNetFilepath);
                        sourceFilePath = downloadNetFilepath;

                        StringBuffer temp = new StringBuffer("http://")
                                .append(ipAddress)
                                .append(":8019/img/")
                                .append(productImgModel.getShopId())
                                .append("/")
                                .append(productId)
                                .append("/net/")
                                .append(productImgModel.getUuidFileName())
                                .append(".")
                                .append(tempInt)
                                .append(".png");

                        sourceFilePathOnNet = temp.toString();
                    }

                    ImageUtil.cutImage(sourceFilePath, cutImgPath
                            , productImgDetailModel.getLeft(),
                            productImgDetailModel.getTop(), productImgDetailModel.getWidth(), productImgDetailModel.getHeight());

                    logger.info("===============cutImgPath==" + cutImgPath);

                    Integer branchId = null;
                    Product p = productMapper.selectByPrimaryKey(productId);
                    if (p != null) {
                        branchId = p.getStoreid();
                    }

                    List<LogProductImgFromUser> productImgList = productService.getProductImgFromUserListFromCorrect(productId);

                    if (productImgList != null && productImgList.size() > 10) {
                        LogProductImgFromUser correctedImg = productImgList.get(0);
                        boolean delResult = delImg(correctedImg.getContSign(), productImgModel.getShopId(), branchId);

                        if (!delResult) {
                            LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                            logShopBaiduImgDel.setImgType(2);
                            logShopBaiduImgDel.setStatus(0);
                            logShopBaiduImgDel.setLogId(correctedImg.getId());

                            logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                        }

                        if (targetProductId != null) {
                            List<LogProductImgFromUser> targetProductImgList = productService.getProductImgFromUserListFromCorrect(targetProductId);

                            if (targetProductImgList != null && targetProductImgList.size() > 10) {
                                LogProductImgFromUser targetCorrectedImg = productImgList.get(0);
                                boolean targetDelResult = delImg(targetCorrectedImg.getContSign(), targetShopId, targetBranchId);

                                if (!targetDelResult) {
                                    LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                                    logShopBaiduImgDel.setStatus(0);
                                    logShopBaiduImgDel.setImgType(2);
                                    logShopBaiduImgDel.setLogId(targetCorrectedImg.getId());

                                    logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                                }


                            }
                        }
                    }

                    String contSign = addImg(productImgModel.getShopId(), cutImgPath,
                            productImgModel.getShopId() + "_" + productId, branchId);

                    List<Map<String, String>> contSignCurList = null;
                    String targetContSing = null;

                    if (DataLoadService.shopBaiduUrlCurListMap != null
                            && DataLoadService.shopBaiduUrlCurListMap.get(productImgModel.getShopId()) != null) {
                        /*contSingCur = addImgCur(productImgModel.getShopId(), cutImgPath,
                                productImgModel.getShopId() + "_" + productId, branchId);*/
                        contSignCurList = addImgCurList(productImgModel.getShopId(), cutImgPath,
                                productImgModel.getShopId() + "_" + productId, branchId);
                    }
                    if (targetProductId != null) {
                        targetContSing = addImg(targetShopId, cutImgPath,
                                targetShopId + "_" + targetProductId, targetBranchId);
                    }

                    if (contSign != null) {
                        LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
                        logProductImgFromUser.setContSign(contSign);
                        logProductImgFromUser.setCreateTime(new Date());
                        logProductImgFromUser.setCutImg(cutImgPath);
                        logProductImgFromUser.setSourceImg(productImgModel.getSourceFilename());
                        logProductImgFromUser.setProductId(productId);
                        logProductImgFromUser.setShopId(productImgModel.getShopId());
                        logProductImgFromUser.setFromCorrect(1);
                        logProductImgFromUser.setBranchId(branchId);
                        logProductImgFromUser.setBaiduDeleted(0);
                        logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                        logProductImgFromUser.setImgSrcNetUrl(sourceFilePathOnNet);
                        logProductImgFromUser.setSubDb(0);


                        logProductImgFromUserMapper.insert(logProductImgFromUser);
                    }

                    if (contSignCurList != null && contSignCurList.size() > 0) {
                        for (Map<String, String> map : contSignCurList) {
                            String appid = map.get("appid");
                            String contSignCur = map.get("contSign");
                            LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
                            logProductImgFromUser.setContSign(contSignCur);
                            logProductImgFromUser.setCreateTime(new Date());
                            logProductImgFromUser.setCutImg(cutImgPath);
                            logProductImgFromUser.setSourceImg(productImgModel.getSourceFilename());
                            logProductImgFromUser.setProductId(productId);
                            logProductImgFromUser.setShopId(productImgModel.getShopId());
                            logProductImgFromUser.setFromCorrect(1);
                            logProductImgFromUser.setBranchId(branchId);
                            logProductImgFromUser.setBaiduDeleted(0);
                            logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                            logProductImgFromUser.setImgSrcNetUrl(sourceFilePathOnNet);
                            logProductImgFromUser.setSubDb(1);
                            logProductImgFromUser.setBaiduAppId(appid);


                            logProductImgFromUserMapper.insert(logProductImgFromUser);
                        }

                        Condition productSubCondition = new Condition(ProductSub.class);
                        productSubCondition.or().andEqualTo("productId", productId);

                        List<ProductSub> productSubList = productSubMapper.selectByCondition(productSubCondition);

                        if (productSubList == null || productSubList.size() == 0) {
                            ProductSub productSub = new ProductSub();
                            productSub.setBranchId(branchId);
                            productSub.setShopId(productImgModel.getShopId());
                            productSub.setCreateTime(new Date());
                            productSub.setProductId(productId);

                            productSubMapper.insertSelective(productSub);
                        }
                    }

                    if (targetContSing != null) {
                        LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
                        logProductImgFromUser.setContSign(targetContSing);
                        logProductImgFromUser.setCreateTime(new Date());
                        logProductImgFromUser.setCutImg(cutImgPath);
                        logProductImgFromUser.setSourceImg(productImgModel.getSourceFilename());
                        logProductImgFromUser.setProductId(targetProductId);
                        logProductImgFromUser.setShopId(targetShopId);
                        logProductImgFromUser.setFromCorrect(1);
                        logProductImgFromUser.setBranchId(branchId);
                        logProductImgFromUser.setBaiduDeleted(0);
                        logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                        logProductImgFromUser.setImgSrcNetUrl(sourceFilePathOnNet);
                        logProductImgFromUser.setSubDb(0);


                        logProductImgFromUserMapper.insert(logProductImgFromUser);
                    }
                }
            }

            logger.info("===============end=====correctProductImg");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void correctProductImgCur(ProductCorrectForm productCorrectForm) {

        if (productCorrectForm.getItemList() == null || productCorrectForm.getItemList().size() == 0) {
            return;
        }

        logger.info("===============start =====correctProductImg");
        try {
            ProductImgModel productImgModel = getProductImgFromCache(productCorrectForm.getProductOrderNo());

            if (productImgModel == null) {
                return;
            }


            if (productImgModel.getItemList() != null && productImgModel.getItemList().size() > 0) {
                int i = 0;

                Map<Integer, ProductImgDetailModel> productImgDetailModelMap = new HashMap<>();

                Map<Integer, ProductCorrectItemForm> productCorrectItemFormHashMap = new HashMap<>();


                for (ProductCorrectItemForm productCorrectItemForm : productCorrectForm.getItemList()) {
                    productCorrectItemFormHashMap.put(productCorrectItemForm.getSeq(), productCorrectItemForm);
                }

                Map<Integer, Integer> productIdMap = new HashMap<>();
                for (ProductImgDetailModel productImgDetailModel : productImgModel.getItemList()) {
                    ProductCorrectItemForm productCorrectItemForm = productCorrectItemFormHashMap.get(productImgDetailModel.getSeq());

                    if (productCorrectItemForm != null) {
                        productIdMap.put(productCorrectItemForm.getProductId(), productImgDetailModel.getProductId());

                        productImgDetailModel.setProductId(productCorrectItemForm.getProductId());
                        productImgDetailModel.setProductName(productCorrectItemForm.getProductName());

                        productImgDetailModelMap.put(productImgDetailModel.getSeq(), productImgDetailModel);
                    }
                }

                String productImgModeStr = JsonUtil.toJson(productImgModel);
                logger.info(productImgModeStr);

                /**
                 * save to cache and db
                 */
                setKey(productCorrectForm.getProductOrderNo(), productImgModel, 60 * 60 * 1000);
                ProductImgJsonInfo productImgJsonInfo = new ProductImgJsonInfo();
                productImgJsonInfo.setProductContent(productImgModeStr);

                Condition condition = new Condition(ProductImgJsonInfo.class);
                condition.or().andEqualTo("productOrderNo", productCorrectForm.getProductOrderNo());
                productImgJsonInfoMapper.updateByConditionSelective(productImgJsonInfo, condition);
                //---end save---

                List<Integer> productIdList = null;
                if(DataLoadService.shopYpProductListMap != null){
                    List<ProductYpRef> temp = DataLoadService.shopYpProductListMap.get(productImgModel.getShopId());

                    if (temp != null && temp.size() > 0) {
                        productIdList = temp.stream().map(ProductYpRef::getProductId).collect(Collectors.toList());
                    }
                }

                for (ProductCorrectItemForm productCorrectItemForm : productCorrectForm.getItemList()) {
                    if (productIdList != null && productIdList.contains(productCorrectItemForm.getProductId())) {
                        logger.info("忽略云澎菜品库商品:" + productCorrectItemForm.getProductName());
                        continue;
                    }


                    ProductImgDetailModel productImgDetailModel = productImgDetailModelMap.get(productCorrectItemForm.getSeq());

                    Integer productId = productCorrectItemForm.getProductId();

                    if (productId != 1) {
                        /**
                         * 删除旧图片
                         */

                        logger.info("删除旧图片productId=" + productId);

                        ThreadManager.executorService.submit(() -> {
                            deleteProductImg(productId);
                        });
                    }

                    if (productImgDetailModel.getScore() > 0.75) {
                        Integer oldProductId = productIdMap.get(productId);
                        if (oldProductId != 1) {
                            logger.info("被修改的菜品分数大于0.75,删除旧图片oldProductId=" + oldProductId);
                            ThreadManager.executorService.submit(() -> {
                                deleteProductImg(oldProductId);
                            });
                        }
                    }


                    String localFilepath = "/usr/local/nginx/html/img/" + productImgModel.getShopId() + "/" + productId;

                    File imgCutFile = new File(localFilepath);
                    if (!imgCutFile.exists()) {
                        imgCutFile.mkdir();
                    }
                    localFilepath += "/temp";

                    File imgCutFileTemp = new File(localFilepath);
                    if (!imgCutFileTemp.exists()) {
                        imgCutFileTemp.mkdir();
                    }

                    StringBuffer cutImgUrl = new StringBuffer("http://")
                            .append(ipAddress)
                            .append(":8019/img/")
                            .append(productImgModel.getShopId())
                            .append("/")
                            .append(productId)
                            .append("/temp/")
                            .append(productImgModel.getUuidFileName())
                            .append("_cut")
                            .append(i)
                            .append(".png");

                    String cutImgPath = localFilepath + "/" + productImgModel.getUuidFileName() + "_cut" + i + ".png";
                    i++;

                    String sourceFilePath = productImgModel.getSourceFilename();
                    String sourceFilePathOnNet = productImgModel.getSourceImgOnInternet();
                    if (productImgModel.getCurIpAddress() != null &&
                            productImgModel.getCurIpAddress().equals(ipAddress)
                            ) {
                        LoggerUtil.console.info("source file ip : {}, sourceFilePath:", productImgModel.getCurIpAddress(), sourceFilePath);
                    } else {
                        LoggerUtil.console.info("source file ip : {}", productImgModel.getCurIpAddress());

                        String downloadNetFilepath = "/usr/local/nginx/html/img/" + productImgModel.getShopId() + "/" + productId + "/net";

                        File downloadNetFilepathFile = new File(downloadNetFilepath);
                        if (!downloadNetFilepathFile.exists()) {
                            downloadNetFilepathFile.mkdir();
                        }

                        int tempInt = new Random(100).nextInt();
                        downloadNetFilepath += "/" + productImgModel.getUuidFileName() + "." + tempInt + ".png";
                        ImageBase64Util.downloadNetImage(productImgModel.getSourceImgOnInternet(), downloadNetFilepath);

                        LoggerUtil.console.info("source file ip : {}, sourceFilePath:{}",
                                productImgModel.getCurIpAddress(), downloadNetFilepath);
                        sourceFilePath = downloadNetFilepath;

                        StringBuffer temp = new StringBuffer("http://")
                                .append(ipAddress)
                                .append(":8019/img/")
                                .append(productImgModel.getShopId())
                                .append("/")
                                .append(productId)
                                .append("/net/")
                                .append(productImgModel.getUuidFileName())
                                .append(".")
                                .append(tempInt)
                                .append(".png");

                        sourceFilePathOnNet = temp.toString();
                    }

                    ImageUtil.cutImage(sourceFilePath, cutImgPath
                            , productImgDetailModel.getLeft(),
                            productImgDetailModel.getTop(), productImgDetailModel.getWidth(), productImgDetailModel.getHeight());

                    logger.info("===============cutImgPath==" + cutImgPath);

                    Integer branchId = null;
                    Product p = productMapper.selectByPrimaryKey(productId);
                    if (p != null) {
                        branchId = p.getStoreid();
                    }
                    String contSign = addImg(productImgModel.getShopId(), cutImgPath,
                            productImgModel.getShopId() + "_" + productId, branchId);

                    if (contSign != null) {
                        LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
                        logProductImgFromUser.setContSign(contSign);
                        logProductImgFromUser.setCreateTime(new Date());
                        logProductImgFromUser.setCutImg(cutImgPath);
                        logProductImgFromUser.setSourceImg(productImgModel.getSourceFilename());
                        logProductImgFromUser.setProductId(productId);
                        logProductImgFromUser.setShopId(productImgModel.getShopId());
                        logProductImgFromUser.setFromCorrect(1);
                        logProductImgFromUser.setBaiduDeleted(0);
                        logProductImgFromUser.setImgCutNetUrl(cutImgUrl.toString());
                        logProductImgFromUser.setImgSrcNetUrl(sourceFilePathOnNet);


                        logProductImgFromUserMapper.insert(logProductImgFromUser);
                    }
                }
            }

            logger.info("===============end=====correctProductImg");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public ProductImgModel getProductImgFromCache(String productOrderNo) {
        try {
            ProductImgModel productImgModel = (ProductImgModel) getKey(productOrderNo);

            if (productImgModel == null) {
                Condition condition = new Condition(ProductImgJsonInfo.class);

                condition.or().andEqualTo("productOrderNo", productOrderNo);
                List<ProductImgJsonInfo> productImgJsonInfoList = productImgJsonInfoMapper.selectByCondition(condition);

                if (productImgJsonInfoList != null && productImgJsonInfoList.size() > 0) {
                    productImgModel =
                            JsonUtil.parse(productImgJsonInfoList.get(0).getProductContent(), ProductImgModel.class);
                } else {
                    return null;
                }
            }

            return productImgModel;
        } catch (Exception e) {

            e.printStackTrace();
            return null;
        }
    }

    public boolean delImg(String cont_sign, Integer shopId, Integer branchId) {

        String token = getBaiduToken(shopId, branchId);

        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/delete?access_token=" + token;


        String param = "cont_sign=" + cont_sign + "&sub_lib=" + getKey(baiduAppidKey + shopId + branchId);

        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            logger.info(result.getBody());
            /**
             * {"log_id": 379096853819015407, "cont_sign": "2743144346,4232638351"}
             */

            Map<String, Object> m = JsonUtil.parse(result.getBody(), Map.class);

            if (m.get("log_id") != null && !m.containsKey("error_code")) {
                return true;
            }

            if (m.containsKey("error_code")) {
                Integer errorCode = (Integer) m.get("error_code");
                if (errorCode.equals(216680)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


    public boolean delImgCur(String cont_sign, Integer shopId, Integer branchId) {

        Map<String, String> tokenMap = getBaiduTokenCur(shopId, branchId);
        String token = tokenMap.get("token");
        String appId = tokenMap.get("appId");

        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/delete?access_token=" + token;

        String param = "cont_sign=" + cont_sign + "&sub_lib=" + appId;

        try {
            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

            logger.info(result.getBody());
            /**
             * {"log_id": 379096853819015407, "cont_sign": "2743144346,4232638351"}
             */

            Map<String, Object> m = JsonUtil.parse(result.getBody(), Map.class);

            if (m.get("log_id") != null && !m.containsKey("error_code")) {
                return true;
            }

            if (m.containsKey("error_code")) {
                Integer errorCode = (Integer) m.get("error_code");
                if (errorCode.equals(216680)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public boolean delImgCurList(String cont_sign, Integer shopId, Integer branchId, String appid) {

        List<Map<String, String>> tokenList = getBaiduTokenCurList(shopId, branchId);

        if (tokenList != null) {
            for (Map<String, String> map : tokenList) {
                String token = map.get("token");
                String dbappid = map.get("appid");

                if (StringUtils.isEmpty(appid)) {
                    appid = dbappid;
                }
                if (dbappid.equals(appid)) {
                    String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/delete?access_token=" + token;


                    String param = "cont_sign=" + cont_sign + "&sub_lib=" + dbappid;

                    try {
                        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
                        MediaType jsontype = MediaType.APPLICATION_FORM_URLENCODED;
                        DEFAULT_JSON_HEADER.setContentType(jsontype);

                        HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

                        ResponseEntity<String> result = new RestTemplate().postForEntity(url, entity, String.class);

                        logger.info(result.getBody());
                        /**
                         * {"log_id": 379096853819015407, "cont_sign": "2743144346,4232638351"}
                         */

                        Map<String, Object> m = JsonUtil.parse(result.getBody(), Map.class);

                        if (m.get("log_id") != null && !m.containsKey("error_code")) {
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }



        return false;
    }

    @Resource
    public ProductService productService;

    public void deleteProductImg(Integer productId){
        /*List<LogProductImg> logProductImgList = productService.getProductImgList(productId);
        if (logProductImgList != null) {
            List<Integer> productImgIdList = new ArrayList<>();

            logProductImgList.stream().forEach(p -> {
                if(delImg(p.getContSign(), p.getShopId())){
                    productImgIdList.add(p.getId());
                }
            });

            if (productImgIdList.size() > 0) {
                productService.deleteProductImgList(productImgIdList);
            }
        }*/

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -2);

        List<LogProductImgFromUser> logProductImgFromUserList = productService.getProductImgFromUserList(productId);
        if (logProductImgFromUserList != null) {
            List<Integer> productImgIdList = new ArrayList<>();
            logProductImgFromUserList.stream().forEach(p -> {
                if (p.getFromCorrect() != null && p.getFromCorrect().intValue() == 1) {

                    if (p.getCreateTime().after(calendar.getTime())) {
                        logger.info("一周内的纠正不删除:" + p.getId() + ", productId:" + p.getProductId());
                    }else {
                        logger.info("删除:" + p.getContSign() + ", productId:" + p.getProductId());
                        if(delImg(p.getContSign(), p.getShopId(), p.getBranchId())){
                            productImgIdList.add(p.getId());
                        }else {
                            LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                            logShopBaiduImgDel.setLogId(p.getId());
                            logShopBaiduImgDel.setStatus(0);

                            logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                        }
                    }
                }else {
                    logger.info("删除:" + p.getContSign() + ", productId:" + p.getProductId());
                    if(delImg(p.getContSign(), p.getShopId(), p.getBranchId())){
                        productImgIdList.add(p.getId());
                    }else {
                        LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                        logShopBaiduImgDel.setLogId(p.getId());
                        logShopBaiduImgDel.setStatus(0);

                        logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                    }
                }
            });

            if (productImgIdList.size() > 0) {
                productService.deleteProductImgFromUserList(productImgIdList);

            }
        }

    }

    public void deleteProductImgCur(Integer productId){
        /*List<LogProductImg> logProductImgList = productService.getProductImgList(productId);
        if (logProductImgList != null) {
            List<Integer> productImgIdList = new ArrayList<>();

            logProductImgList.stream().forEach(p -> {
                if(delImg(p.getContSign(), p.getShopId())){
                    productImgIdList.add(p.getId());
                }
            });

            if (productImgIdList.size() > 0) {
                productService.deleteProductImgList(productImgIdList);
            }
        }*/

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -2);

        List<LogProductImgFromUser> logProductImgFromUserList = productService.getProductImgFromUserList(productId);
        if (logProductImgFromUserList != null) {
            List<Integer> productImgIdList = new ArrayList<>();
            logProductImgFromUserList.stream().forEach(p -> {
                if (p.getFromCorrect() != null && p.getFromCorrect().intValue() == 1) {

                    if (p.getCreateTime().after(calendar.getTime())) {
                        logger.info("一周内的纠正不删除:" + p.getId() + ", productId:" + p.getProductId());
                    }else {
                        logger.info("删除:" + p.getContSign() + ", productId:" + p.getProductId());
                        boolean deleted;
                        if (p.getSubDb() == null || p.getSubDb() == 0) {
                            deleted = delImg(p.getContSign(), p.getShopId(), p.getBranchId());
                        }else {
                            deleted = delImgCurList(p.getContSign(), p.getShopId(), p.getBranchId(), p.getBaiduAppId());
//                            deleted = delImgCur(p.getContSign(), p.getShopId(), p.getBranchId());
                        }
                        if(deleted){
                            productImgIdList.add(p.getId());
                        }else {
                            LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                            logShopBaiduImgDel.setStatus(0);
                            logShopBaiduImgDel.setLogId(p.getId());

                            logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                        }
                    }
                }else {
                    logger.info("删除:" + p.getContSign() + ", productId:" + p.getProductId());
                    boolean deleted;
                    if (p.getSubDb() == null || p.getSubDb() == 0) {
                        deleted = delImg(p.getContSign(), p.getShopId(), p.getBranchId());
                    }else {
                        deleted = delImgCurList(p.getContSign(), p.getShopId(), p.getBranchId(), p.getBaiduAppId());
//                        deleted = delImgCur(p.getContSign(), p.getShopId(), p.getBranchId());
                    }
                    if(deleted){
                        productImgIdList.add(p.getId());
                    }else {
                        LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                        logShopBaiduImgDel.setLogId(p.getId());
                        logShopBaiduImgDel.setStatus(0);

                        logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                    }
                }
            });

            if (productImgIdList.size() > 0) {
                productService.deleteProductImgFromUserList(productImgIdList);

            }
        }

    }



    public boolean reRecognize(Integer shopId, String cutImgPath, Integer verifyProductId, Integer branchId){
        try {
            String token = getBaiduToken(shopId, branchId);

            String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token=" + token;

            String fileBase64Content = ImageBase64Util.getImageBinary(cutImgPath);
//        byte[] imgData = com.binguo.api.webapi_tts.FileUtil.read(filename);
//        String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(fileBase64Content, "UTF-8");

            String param = "image=" + imgParam + "&top_num=" + 5;

            HttpEntity<String> entity = new HttpEntity<>(param, DEFAULT_JSON_HEADER);

            ResponseEntity<String> result = restTemplate.postForEntity(url, entity, String.class);

            logger.info(result.getBody());

            BaiduSearchResult baiduSearchResult = JsonUtil.parse(result.getBody(), BaiduSearchResult.class);

            if (baiduSearchResult != null) {
                List<Result> searchResultList = baiduSearchResult.getResult();

                if (searchResultList != null && searchResultList.size() > 0) {

                    for (Result temp : searchResultList) {
                        List<Dishes> dishesList = temp.getDishes();
                        String shopProductId = null;
                        if (dishesList != null && dishesList.size() > 0) {
                            double score = 0;
                            for (Dishes dishes : dishesList) {
                                if (dishes.getScore() > score) {
                                    shopProductId = dishes.getBrief();
                                    score = dishes.getScore();
                                }
                            }

                            if (score > 0.75) {
                                Integer productId = null;
                                if (shopProductId.contains("_")) {
                                    productId = Integer.valueOf(shopProductId.split("_")[1]);
                                }

                                if (productId != null && verifyProductId.intValue() == productId.intValue()) {
                                    return true;
                                }
                            }

                        }
                    }
                }
            }
        } catch (Exception e) {
            LoggerUtil.console.error(e.getMessage());
        }

        return false;
    }
}
